This article shows some code examples with an idea of each milestone. All examples are just my own idea, it means it is not the only solution and can be wrong. There are a lot of better approaches for solving the problems. Just refer it as one way of ideas. If you have a different one, keep going with that!
To postpone the binding of the call to display() until run-time when the executable code is aware of the dynamic type of object p.
Simply, in the situation that child object is assigned to parent datatype, If you want to use overrided method make the parent function to 'virtual'.
#include <iostream>
class A {
public:
A(){}
void display() {
std::cout << "A" << std::endl;
}
};
class B : public A {
public:
void display() {
std::cout << "B" << std::endl;
}
};
int main() {
A a = A();
B b = B();
A &c = b;
a.display();
b.display();
c.display();
return 0;
}
A
B
A //<--- c is assigned B object, but display() in A is called.
#include <iostream>
class A {
public:
A(){}
virtual void display() {
std::cout << "A" << std::endl;
}
};
class B : public A {
public:
void display() {
std::cout << "B" << std::endl;
}
};
int main() {
A a = A();
B b = B();
A &c = b;
a.display();
b.display();
c.display();
return 0;
}
A
B
B //<--- c is assigned B object, and display() in B is called.