Passing a derived class by reference to a function that takes a base class as a parameter

Consider the following code:

class A { public: virtual ~A() { } virtual void print() const { std::cout << "In A" << std::endl; } }; class B : public A { public: B() { } virtual ~B() { } virtual void print() const { std::cout << "In B" << std::endl; } }; void doSomething(A* a) { a->print(); } void doSomething(const A a) { a.print(); } int main() { A* a = new B(); doSomething(a); doSomething(B()); return 0; } 

Why is this conclusion:

 In B In A 

But when you change doSomething to doSomething(const A& a) , it produces:

 In B In B 
+7
c ++ polymorphism
source share
1 answer

This is called slicing.

When A passed by value, a local copy is created by copying only part A of the calling object. Since it has both static and dynamic type A , an override of print is selected.

Passing by reference, this function receives a reference to the calling object with dynamic type B , so an override is selected.

The use of abstract base classes can prevent the confusion of such behavior - they cannot be directly created and therefore cannot be passed by value.

+10
source share

All Articles