Does polymorphism work in C ++ without pointers / references?

Possible duplicate:
Virtual Functions Object Breakdown

consider:

#include <vector> #include <iostream> using namespace std; struct A { virtual void do_it() { cout << "A" << endl; } }; struct B : public A { virtual void do_it() { cout << "B" << endl; } }; int main() { vector<A> v; v.push_back(B()); v[0].do_it(); // output is A } 

which function will be called? In principle, is it possible to use polymorphism without pointers if there is no cutting?

+7
source share
5 answers

No, this is not possible without pointers.

Since you create object B and click on the vector containing A , it will be copied (sent to copy constructor A ), and instance A will be added to the vector, i.e. the object will be sliced.

Given this code:

 struct A { virtual void d() { std::cout << "Hello A" << std::endl; } }; struct B : public A { virtual void d() { std::cout << "Hello B" << std::endl; } }; int main() { std::vector<A> v; v.push_back(B()); v[0].d(); } 

The output will be:

 Hello A 
+13
source

The problem is that there is slicing in your example. Using push_back is somehow equivalent:

 A array[N]; array[last++] = B(); 

In the second line, where you have slicing, since each position in the array can contain an object of type A , but not one of type B

You can use pointers to solve this problem by defining v as std::vector<A*> v . It is probably best to use smart pointers (either those that are present in C ++ 11 , or those that are listed in Boost ).

+6
source

Does polymorphism work in C ++ without pointers / references?

Yes and no.

Dynamic polymorphism works in C ++ when the static type of a pointer or reference may differ from the dynamic type of the object to which it refers, and the behavior is selected based on the dynamic type. This requires pointers or references, since the object itself has only one type.

Static polymorphism, using templates, works great with objects, but solves a different class of problems. In your example, dynamic polymorphism is required to select behavior based on the runtime type of objects.

which function will be called?

The vector contains objects of type A , so A::do_it() will be called. The object does not know that it was created by slicing an object of type B

In principle, is it possible to use polymorphism without pointers if there is no cutting?

Slicing is always present when you create objects of a base class from objects of a derived class. This is the definition of cutting.

+5
source

Does polymorphism work in C ++ without pointers / references?

Yes. See static polymorphism .

In your case, the base function will be called, but polymorphism does not work correctly. Polymorphism is guaranteed to work, simply because you do not use it. What you have is basically a collection of A. objects.

+5
source

This will not work, as sizeof (parent) will not always be equal to sizeof (child)

0
source

All Articles