Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Base class method through base class pointer pointing to derived class

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? */
}
like image 400
coolcake Avatar asked Jul 16 '09 08:07

coolcake


People also ask

Can a base class pointer call methods in the derived class?

// As base-class pointer cannot access the derived class variable.

Can we call methods of base class using the constructor of the derived class?

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.

How do you call a method of base class in derived class in Java?

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();


1 Answers

pBase->Base::foo()
like image 192
polyglot Avatar answered Oct 22 '22 01:10

polyglot