Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call virtual method from base class on object of derived type

Tags:

c++

class Base
{
public:
    virtual void foo() const
    {
        std::cout << "Base";
    }
};

class Derived : public Base
{
public:
    virtual void foo() const
    {
        std::cout << "Derived";
    }
};

Derived d; // call Base::foo on this object

Tried casting and function pointers but I couldn't do it. Is it possible to defeat virtual mechanism (only wondering if it's possible)?

like image 970
Nikola Smiljanić Avatar asked May 07 '10 10:05

Nikola Smiljanić


People also ask

How do you call a virtual function from a derived class?

A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.

Can we call derived class method from base class?

Even though the derived class can't call it in the base class, the base class can call it which effectively calls down to the (appropriate) derived class. And that's what the Template Method pattern is all about.

Can a base class object access the methods of derived class?

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

Can you assign a derived class object to a base class object?

In C++, a derived class object can be assigned to a base class object, but the other way is not possible.


1 Answers

To explicitly call the function foo() defined in Base, use:

d.Base::foo();
like image 53
Daniel Daranas Avatar answered Oct 25 '22 09:10

Daniel Daranas