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
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
Asked: 2023-06-28 14:38:49 +0000
Seen: 20 times
Last updated: Jun 28 '23
How to provide parameters to machine learning model objects?
Is it impossible to delete any objects provided by ActiveRecord_Associations_CollectionProxy?
What is the technique for creating a mapping of an array containing various objects and values?
How can an array of objects be initialized in C# without implementing a loop?
Is it possible to retrieve objects as a list in jq in order to access them by index?
How to query an array of objects with JSONB in Postgres?
How can the clipping of objects in matplotlib 3D be modified?
In Laravel, what is the process for comparing two objects and obtaining distinct columns?