I'm learning c++ and to start off i thought it might be a good experience to port some of my code. but i have come to a standstill on how one would do somthing like this in c++.
class Class1 {}
class Class2 {}
class Class3 : Class2 { }
class IsTest
{
staticvoid Test(object o)
{
Class1 a;
Class2 b;
if (o is Class1)
{
Console.WriteLine("o is Class1");
a = (Class1)o;
// Do something with "a."
}
elseif (o is Class2)
{
Console.WriteLine("o is Class2");
b = (Class2)o;
// Do something with "b."
}
else
{
Console.WriteLine("o is neither Class1 nor Class2.");
}
}
staticvoid Main()
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
Class3 c3 = new Class3();
Test(c1);
Test(c2);
Test(c3);
Test("a string");
}
}
struct A
{
virtual ~A(){}
};
struct B : A {}
A *pa = new B();
B *pb = dynamic_cast<B *>( pa );
if ( pb != nullptr ) std::cout << "pa refers an object of type B";
#include <typeinfo>
//...
A* ptr = new B;
if(typeid(*ptr) == typeid(B))
{
// ptr points to a 'B' object
}
As with vlad's example... the parent class must be polymorphic (must have at least 1 virtual member).
That said... this is bad design and you should avoid it. The point of inheritance is to treat all derived classes the same. If you're not going to treat them the same you probably shouldn't be referring to them with base class pointer/reference in the first place.
What i'm making is a some network code that will be use by the server and client. and seeing that the server has some slight difference with the client (extra actions) i put that is there to i know which class is running .
so if this is a bad design what would be a better technique to use?