c# is equivalent in c++

Hi,

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++.

 
(o is Class2)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  class Class1 {}
class Class2 {}
class Class3 : Class2 { }

class IsTest
{
    static void Test(object o)
    {
        Class1 a;
        Class2 b;

        if (o is Class1)
        {
            Console.WriteLine("o is Class1");
            a = (Class1)o;
            // Do something with "a."
        }
        else if (o is Class2)
        {
            Console.WriteLine("o is Class2");
            b = (Class2)o;
            // Do something with "b."
        }

        else
        {
            Console.WriteLine("o is neither Class1 nor Class2.");
        }
    }
    static void Main()
    {
        Class1 c1 = new Class1();
        Class2 c2 = new Class2();
        Class3 c3 = new Class3();
        Test(c1);
        Test(c2);
        Test(c3);
        Test("a string");
    }
}
You can use something as

1
2
3
4
5
6
7
8
9
10
11
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";
Another alternative:

1
2
3
4
5
6
7
8
9
10
#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.
Disch: i don't really understand your warning.

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?
Topic archived. No new replies allowed.