How to make that typeid returns the type of object child

Hi!
I have the class ' Component' with a std::string variable, 'name' that his value is typeid(this).name(), call from constructor.

The problem is that when a class inherits from Component remains typeid 'Component'. If I want the name of the Cube was 'Cube', but from the function of Component ... How could I?

Component

1
2
3
4
5
6
7
8
9
10
11
12
13
std::string name;

Component::Component()
{
   generateUniqueName();
}    

void generateUniqueName(void)
{
  name = typeid(this).name();
  cout<<name<<endl;
}
}


Cube
1
2
3
4
class Cube : public Component
{

}


output:
Component

And I want that the name is 'Cube'.
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
#include <iostream>
#include <string>

class Component
{
public:
    // Must have polymorphic behavior.
    virtual ~Component() {}

    std::string getType() const
    {
        // must dereference the pointer to get at the polymorphic type.
        return typeid(*this).name() ;
    }
};

class Cube : public Component
{
};

int main()
{
    Component component ;
    Cube cube ;
    Component * c = &cube ;

    std::cout << "component: " << component.getType()
              << "\ncube: " << cube.getType()
              << "\nc: " << c->getType() << '\n' ;
}
component: class Component
cube: class Cube
c: class Cube

Yes, if a call the function in main(), this returns the class correctly. But I need call this function from the constructor of Component. I need that the name generation is automatic.
But I need call this function from the constructor of Component.


Then I'm afraid you're going to need to change your design so you don't need that.
Topic archived. No new replies allowed.