#include <iostream>
#include <vector>
using namespace std;
class Parent {
public:
Parent();
void method();
};
class Child: public Parent {
public:
Child();
void method();
};
int main() {
vector<Parent> v;
v.push_back(Parent());
v.push_back(Child());
v[0].method();
v[1].method();
return 0;
}
Parent::Parent() {}
void Parent::method() {
cout << "Parent." << endl;
}
Child::Child() {}
void Child::method() {
cout << "Child." << endl;
}
Basically I’d expect that program to print
Parent.
Child.
but it prints this instead:
Parent.
Parent.
C++ surprises me yet again :).
Why does this happen? What can I do to call Child::method for instances of Child in the vector, and Parent::method for instances of Parent?
I’m using gcc:
gcc version 4.6.1 20110819 (prerelease) (GCC)
like this:
g++ -Wall -Wextra -c main.cpp
g++ -Wall -Wextra -o main main.o
You are encountering the slicing problem.
vector<Parent>.push_back()copies its argument, so it invokesParent::Parent(const Parent &)(i.e. the copy constructor)*.This is really no different to:
* Or it might be
Parent::operator=(const Parent &), i.e. copy-assignment. I’m tired, and I can’t remember which it needs.