mercredi 24 avril 2019

C++ When called Child function it is instead calling the Parent function

I am working on a project where I have an array of children classes. I want to call an overridden child function from the array, but instead call the parent function instead.

#include <iostream>

class Parent {
public:
    Parent(){}
    void print() {
        std::cout << "I'm the parent!" << std::endl;
    }
};

class ChildOne : public Parent {
public:
    ChildOne(){}
    void print() {
        std::cout << "I'm childOne!" << std::endl;
    }
};

class ChildTwo : public Parent {
public:
    ChildTwo() {}
    void print() {
        std::cout << "I'm childTwo!" << std::endl;
    }
};


int main(int argc, char const *argv[]) {
    Parent arr[] = {ChildOne(), ChildTwo()};
    int n = 2;

    for(int i = 0; i < n; i++) {
        arr[i].print();
    }

    return 0;
}


The output I get is

I'm the parent!
I'm the parent!

Where the output I want is

I'm childOne!
I'm childTwo!

Aucun commentaire:

Enregistrer un commentaire