Well, you could use a
dynamic_cast
, try for instance
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
A(int a):a{a}{}
virtual void show(){ cout << "A " << a << "\n"; }
};
class AB : public A
{
public:
AB(int a):A{a}{}
void show() override { cout << "AB " << a << "\n"; }
};
class AC : public A
{
public:
AC(int a):A{a}{}
void show() override { cout << "AC " << a << "\n"; }
};
int main()
{
A a{10};
AB ab{20};
AC ac(30);
cout << "enter your choice: ";
int choice;
cin >> choice;
switch(choice)
{
case 0:
break;
case 1:
{
auto refAB = dynamic_cast<AB &>(ab); refAB.show();
}
break;
case 2:
{
auto refAB = dynamic_cast<AB &>(a); refAB.show();
}
break;
case 3:
{
auto refAB = dynamic_cast<AB &>(ac); refAB.show();
}
break;
default:
break;
}
}
Anyway, such behaviors are usually implemented using
polymorphism.