It is very common to use pointer to achieve polymorphism. For example,
#include <iostream>
using namespace std;
// Base class
class A {
public:
virtual void output() = 0;
};
// Derived class B
class B : public A {
public:
void output() override {
cout << "From derived class B" << endl;
}
};
// Derived class C
class C : public A {
public:
void output() override {
cout << "From derived class C" << endl;
}
};
// Client code
int main(int argc, char** argv)
{
A *b = new B;
A *c = new C;
int flag = 0;
cin >> flag;
auto t = flag == 0 ? b : c;
t->output();
delete b;
delete c;
return 0;
}
Build the above code, and test it.
g++ -o testrefer main.cpp --std=c++14
./testrefer
0
From the derived class B
./testrefer
1
From the derived class C
What if there are two objects of derived classes instead of two pointers of them in the client code? The answer is using reference.
// Client code
int main(int argc, char** argv)
{
B b;
C c;
int flag = 0;
cin >> flag;
auto& t = flag == 0 ? static_cast< A& >( b ) : static_cast< A& >( c );
t.output();
return 0;
}
Build and test it, and get the same output.
g++ -o testrefer main.cpp --std=c++14
./testrefer
0
From the derived class B
./testrefer
1
From the derived class C