Calling method of child class on a vector of parent class

风格不统一 提交于 2019-12-10 18:21:22

问题


#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

回答1:


You are encountering the slicing problem.

vector<Parent>.push_back() copies its argument, so it invokes Parent::Parent(const Parent &) (i.e. the copy constructor)*.

This is really no different to:

Parent x[10];

x[0] = Parent();
x[1] = Child();

* Or it might be Parent::operator=(const Parent &), i.e. copy-assignment. I'm tired, and I can't remember which it needs.




回答2:


The vector stores Parents, not Childrens.

If you want to take advantage of polymorphism, store pointers instead... but be damned sure that it's what you want.



来源:https://stackoverflow.com/questions/7313622/calling-method-of-child-class-on-a-vector-of-parent-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!