1

What is the meaning of the following in Bjarne Stroustrup's The C++ Programming Language Fourth Edition?

"Consider . (dot) suspect when applied to something that is supposed to be run-time polymorphic unless it is obviously applied to a reference."

Juni Liu
  • 13
  • 2

1 Answers1

0

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270