class Base
{
public:
virtual void foo()
{}
};
class Derived: public Base
{
public:
virtual void foo()
{}
};
int main()
{
Base *pBase = NULL;
Base objBase;
Derived objDerived;
pBase = &objDerived;
pBase->foo();
/*Here Derived class foo will be called, but i want this to call
a base class foo. Is there any way for this to happen? i.e. through
casting or something? */
}
// As base-class pointer cannot access the derived class variable.
12. Can we call methods of base class using the constructor of the derived class? Explanation: If the function is defined in the base class, it can always be called from the constructor of its derived class. Since the constructors are not private, they can be accessed in derived class even if those are protected.
Base baseRef = new derived(); // Due to dynamic binding, will call the derived class // display() function baseRef. display(); Base baseRef = new derived(); // Due to dynamic binding, will call the derived class // display() function baseRef. display();
pBase->Base::foo()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With