Possible Duplicate:
Virtual Functions Object Slicing
let’s 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? Basically is it possible to use polymorphism without pointers if no slicing is present?
No it will not be possible without pointers.
Since you create an object
Band push it to the vector containingA, it will get copied (sent to the copy constructor ofA) and an instance ofAwill be added to the vector. I.e. the object will be sliced.Given this code:
The output will be: