I'm pretty new to object oriented programming in C++, and I can't find a solution to the following problem, I hope this is even possible.
I've got 3 classes: Base
and Child
, Child2
.
All of them got the function talk();
.
I want to store Base
, Child
and Child2
objects in an array, and iterate through them and execute their talk()
functions.
This is what I want them to print:
- Base: "base"
- Child: "child"
- Child2: "child2"
Here are my classes:
class Base {
public:
virtual void talk() {
printf("base\n");
}
}
class Child : public Base {
public:
using Base:draw;
void talk() {
printf("child\n");
}
}
class Child2 : public Base {
public:
using Base:draw;
void talk() {
printf("child2\n");
}
}
here is my array:
Base objects[3];
objects[0] = Base();
objects[1] = Child();
objects[2] = Child2();
for(int i = 0; i < 3; i++) {
objects[i]->talk();
}
And the output should be:
base
child
child2