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)?
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.
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.
// As base-class pointer cannot access the derived class variable.
In C++, a derived class object can be assigned to a base class object, but the other way is not possible.
To explicitly call the function foo()
defined in Base
, use:
d.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