0

So I have a ParentClass and a ChildClass. I have a vector objects. I pushed back two items in it, a ParentClass newparent object and a ChildClass newchild object. I have a for-each loop and I want to access the child version function of the parent function from within this for-each loop but I cant. Please help.

here is the code:

#include <iostream>
#include <vector>

using namespace std;

class ParentClass {
    public:

        int _a;

        ParentClass(int a) {
            this->_a = a;
        }

        void print_a() {
            cout << "parent a: " << this->_a << endl;
        }
};

class ChildClass: public ParentClass {
    public:

        ChildClass(int a) : ParentClass(a) {}

        void print_a(){
            cout << "child a: " << this->_a << endl;
        }
};

int main(int argc, char const *argv[]) {
    int x = 5, y = 6;
    vector<ParentClass> objects;

    ParentClass newparent(x); objects.push_back(newparent);
    ChildClass newchild(y); objects.push_back(newchild);

    for (auto obj : objects){
        obj.print_a();
    }

    return 0;
}

I want it to print out "child a: 6", but it prints out "parent a: 5" and "parent a: 6"

MSalters
  • 167,472
  • 9
  • 150
  • 334

2 Answers2

2

If you have a vector of ParentCLass objects, that will hold ParentClass objects. When you add a ChildClass, C++ will need to apply a conversion - push_back takes ParentCLass const&. The conversion found is the standard child to parent conversion; so the parent part is copied.

This is called "slicing". You can create a std::vector<std::unique_ptr<ParentClass>> instead. This won't slice the object, since the vector only holds (smart) pointers to the objects.

MSalters
  • 167,472
  • 9
  • 150
  • 334
2

Use pointer or reference in you vector in order to use polymorphism , it will not work with copies.

Anis Belaid
  • 310
  • 2
  • 8