This is related to object slicing in C++.
Say you have
struct Base
{
virtual void print() { std::cout << "In Base::print()\n"; }
};
strut Derived : Base
{
virtual void print() { std::cout << "In Derived::print()\n"; }
};
Now you can use them as:
void test(Base base)
{
base.print();
}
int main()
{
Derived d;
test(d);
}
When you use it like that, your program suffers from the object slicing problem. base
in test
does not retain any information about Derived
. It has been sliced to be just a Base
. Hence, the output you will get will correspond to the output of Base::print()
.
If you use:
void test(Base& base)
{
base.print();
}
int main()
{
Derived d;
test(d);
}
the program does not suffer from the object slicing problem. It works polymorphically and the output will correspond to the output from Derived::print()
.
The cautionary note corresponds to use of base.print()
in the first version of test
. It uses the . (dot)
operator on an object that is a polymorphic type, not a reference.