consider the following program:
class Base {
public:
virtual void foo() const {
cout << "Base::foo()" << endl;
}
};
class Derived : public Base {
public:
virtual void foo() {
cout << "Derived::foo()" << endl;
}
};
void func(Base& obj) {
obj.foo();
}
void main() {
Derived d;
func(d); // Base::foo() is printed
}
If I remove the const from the Base class foo method then Derived::foo() is called.
I can’t seem to understand this behavior.
1) What is the reason for this behavior?
2) Is this decided at compile time or runtime?
Thanks
In the derived class, the function signature is this:
which doesn’t mention
const. Its a non-const member function, while theBase::foois a const member function. They’re two different functions, becauseconstis a part of the function signature.Derived class does NOT override this function, instead it adds another function.
So the fix is this:
As
constis a part of the function signature. So you must mention it when you intend to override base’s foo.@davka’s asked:
Its because the static type of
objisBase, and function name is resolved based on the static type of object.Basedoesn’t even have non-const version. So there is no question of it being selected or rejected. It doesn’t exist inBaseto begin with.However, if you change the above code to the following:
Now non-const version will be selected, because
Base::foois hidden inDerivedclass.Since
Derived::foohides theBase::foo, so you cannot call the latter using an instance ofDerived.Now, lets unhide
Base::fooand do some more experiments.Now in Derived, both functions (const as well as non-const version) are available, unhidden. Now few interesting questions.
Since now Derived has both functions unhidden, which function will be called in each function below?
First one will call
Derived::foowhich is non-const version, and second one will callBase::foowhich is const version. The reason is simple, with const object, only const functions can be invoked, but with non-const objects, both can be invoked, however non-const version is selected if its available.See online demo : http://www.ideone.com/955aY