class Base
{
public:
virtual void func() const
{
cout<<"This is constant base "<<endl;
}
};
class Derived : public Base
{
public:
virtual void func()
{
cout<<"This is non constant derived "<<endl;
}
};
int main()
{
Base *d = new Derived();
d->func();
delete d;
return 0;
}
Why does the output prints "This is constant base". However if i remove const in the base version of func(), it prints "This is non constant derived"
d->func() should call the Derived version right, even when the Base func() is const right ?
No, because virtual void func() is not an override for virtual void func() const .
Non-virtual member functions are resolved statically. That is, the member function is selected statically (at compile-time) based on the type of the pointer (or reference) to the object. In contrast, virtual member functions are resolved dynamically (at run-time).
A virtual function is a member function in a base class that can be redefined in a derived class. A pure virtual function is a member function in a base class whose declaration is provided in a base class and implemented in a derived class. The classes which are containing virtual functions are not abstract classes.
const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.
virtual void func() const //in Base
virtual void func() //in Derived
const
part is actually a part of the function signature, which means the derived class defines a new function rather than overriding the base class function. It is because their signatures don't match.
When you remove the const
part, then their signature matches, and then compiler sees the derived class definition of func
as overridden version of the base class function func
, hence the derived class function is called if the runtime type of the object is Derived
type. This behavior is called runtime polymorphism.
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