Ask Your Question
1

What is the method to use a overridden function of child objects in a vector of parent objects?

asked 2023-06-28 14:38:49 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-28 15:08:02 +0000

nofretete gravatar image

The method is to make the function virtual in the parent class and override it in the child class. Then use a pointer to the parent class to point to the child class object and call the virtual function through that pointer. This will automatically call the overridden function in the child class instead of the parent class function.

Here's an example:

#include <iostream>
#include <vector>

using namespace std;

class Parent {
public:
    virtual void foo() {
        cout << "Parent's foo" << endl;
    }
};

class Child : public Parent {
public:
    void foo() override {
        cout << "Child's foo" << endl;
    }
};

int main() {
    vector<Parent*> vec;
    vec.push_back(new Parent());
    vec.push_back(new Child());
    vec.push_back(new Parent());

    for (auto p : vec) {
        p->foo();
    }

    return 0;
}

In the above code, we have two classes Parent and Child. Child inherits from Parent and overrides the foo function. In the main function, we create a vector of Parent pointers but add objects of both Parent and Child classes. Then we loop through the vector and call the foo function through the Parent pointer. Since the foo function is virtual, it is overridden in the Child class and is called when we call it through a Child object. Therefore, the output of the program is:

Parent's foo
Child's foo
Parent's foo
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-28 14:38:49 +0000

Seen: 20 times

Last updated: Jun 28 '23