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
  • 173,980
  • 10
  • 155
  • 350
Mleendox
  • 13
  • 3

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
  • 173,980
  • 10
  • 155
  • 350
  • this worked, thank you. although I ended up using shared_ptr instead – Mleendox Oct 20 '21 at 00:03
  • @LindaniDlamini: I used `unique_ptr` in the assumption that the vector would continue to be the sole owner of the objects, just as it was in your question, but indeed any type of pointer works to obtain polymorphic behavior. – MSalters Oct 20 '21 at 07:46
  • that makes sense. but thank you nontheless – Mleendox Oct 21 '21 at 10:01
2

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

Anis Belaid
  • 304
  • 2
  • 8