The world’s Largest Sharp Brain Virtual Experts Marketplace Just a click Away
Levels Tought:
Elementary,Middle School,High School,College,University,PHD
| Teaching Since: | May 2017 |
| Last Sign in: | 398 Weeks Ago, 6 Days Ago |
| Questions Answered: | 66690 |
| Tutorials Posted: | 66688 |
MCS,PHD
Argosy University/ Phoniex University/
Nov-2005 - Oct-2011
Professor
Phoniex University
Oct-2001 - Nov-2016
In C++, a virtual function may be given a different access level in a derived class. This produces some confusing situations. For example, this is legal C++, at least for some compilers:
class Base {
public:
virtual int f();
};
class Derived: public Base {
private:
virtual int f();
};
This question asks you to explain why this program conflicts with some reasonable principles, yet somehow does not completely break the C++ type system.
(a) In C++, a derived class D with public base class B is treated as a subtype of
B. Explain why this is generally reasonable, given the definition of subtyping from class.
(b) Why would it be reasonable for someone to argue that it is incorrect to allow a public member inherited from a public base class to be redefined as private?
(c) A typical use of subtyping is to apply a function that expects an B argument to a D when D <> B. For example, here is a simple “toy” program that applies a function defined for base-class objects to a derived-class object. Explain why this program compiles and executes for the preceding Base and Derived classes (assuming we have given an implementation for f):
int g(Base &x) {
return(x.f()+1);
}
int main() {
Base b;
cout < “g(b)="”">< g(b)=""> endl; Derived d;
cout < “g(d)="”">< g(d)=""><> endl;
}
(d) Do you think there is a mistake here in the design of C++ ? Briefly explain why or why not.
Hel-----------lo -----------Sir-----------/Ma-----------dam-----------Tha-----------nk -----------You----------- fo-----------r u-----------sin-----------g o-----------ur -----------web-----------sit-----------e a-----------nd -----------and----------- ac-----------qui-----------sit-----------ion----------- of----------- my----------- po-----------ste-----------d s-----------olu-----------tio-----------n.P-----------lea-----------se -----------pin-----------g m-----------e o-----------n c-----------hat----------- I -----------am -----------onl-----------ine----------- or----------- in-----------box----------- me----------- a -----------mes-----------sag-----------e I----------- wi-----------ll