Archived

This topic is now archived and is closed to further replies.

Seriema

howto: knowing the subclass ?

Recommended Posts

Hi! I want to use a Factory to create my subclass objects. I'm thinking about associating the objects with names.
    
class Base
{
protected:
  const static std::string className;  // = "Base"

};


class Sub1 : public Base
{};   // className = "Sub1"



class Sub2 : public Base
{};   // className = "Sub2"



class SubSub2 : public Sub2
{};   // className = "SubSub2"




// somewhere in the code I want a base class pointer to a subclass

Base* pb = Factory::Create("Sub1");  // equal to pb = new Sub1();

    
But it's the names I'm having trouble with. Should the objects themselfs know their names? And if so, how? I thought of the className in Base. But the static will be inherited and overwritten, right? If I make it private, does it get inherited? If so then the subclass can't see it, but defining it's own name... ambiguity? And that would also work against the consistency, if I decide I want a 'className' member then I want it in all classes in the same way. A non-static would solve that but... then everyone would have a name and that's not the point, the name is the class-name. A template thing would help but... inheriting from a templated base member kinda throws away the possibility to std::vector<base*>, right? Why isn't it supported in C++ to object->GetClasName()?? *don't answer this* If anyone's wondering: I'm trying to save class-info on a file, and then read a file and recreate the class. And this subclass thing's kinda tricky. Help! I'm dying here! [edited by - Seriema on May 1, 2003 11:16:03 AM]

Share this post


Link to post
Share on other sites
And if you don''t want to use RTTI but something like it, think about using pure virtual functions in the base class:


class base
{
virtual const char * GetName() = 0;
};


class typeA : public base
{
virtual const char * GetName() { return "typeA"; }
};


class typeB : public base
{
virtual const char * GetName() { return "typeB"; }
};


int main()
{
base *pBase = new typeA;

printf("name: %s\n", pBase->GetName());
}

Share this post


Link to post
Share on other sites
Lantz: yeah I''ll check on that RTTI!

Sphet: thanx for reminding me to KISS :D I''ll go with that for now (until I''ve checked some more on RTTI)

"No lies of sugar can sweeten the sournes of reality"

}+TITANIUM+{ A.K.A. DXnewbie[onMIRC]

Share this post


Link to post
Share on other sites