I am having some unexpected behavior when using references on virtual methods. Basically if I take a reference to an object of the base class, then change that reference to an object of the derived class. When I call the virtual method, the base class method is called.
But if I take a reference to the base class and initialize it to the derived class, the derived method is called. Here is some code.
// A base class with a virtual that prints the class
class BaseClass {
public:
virtual void printMe();
};
class DerivedClass : public BaseClass {
public:
void printMe() override;
};
void BaseClass::printMe() {
cout << "in Base"<<endl;
}
void DerivedClass::printMe() {
cout << "in Derived"<<endl;
}
int main () {
BaseClass bc = BaseClass();
DerivedClass dc = DerivedClass();
BaseClass * pbc = & bc ;
pbc->printMe(); // Prints in Base
pbc = & dc;
pbc->printMe(); // Prints in Derived
// Now with a reference
BaseClass & bcr = bc;
bcr.printMe(); // Prints in Base
bcr = dc;
bcr.printMe(); // Prints in Base !!!
BaseClass & foo = dc;
foo.printMe(); // Prints in Derived !!!
return 0;
}
if someone could explain why the fourth print is not "in Derived" and why the fifth one is "in Derived" I would be grateful.
I (now) understand what has been posted about slicing - but under that logic I don't understand why
BaseClass & foo = dc;
foo.printMe()
calls the derived method
Nevermind I see it now.