[gameprogrammer] Re: Pure virtual function getting called
- From: Ed Sinjiashvili <slimb@xxxxxxxxxxxxxxxxx>
- To: gameprogrammer@xxxxxxxxxxxxx
- Date: Thu, 20 May 2004 09:26:59 +0400
Kevin Jenkins wrote:
> On a similar topic, all GetClassName does is return the name of the class it
> is enclosed in. I made it pure virtual so the users wouldn't forget to
> define it. But if there is an automatic way to do this please let me know.
You could try to tinker with RTTI and templates - though I tend to shy
away using them. Here's an ugly example of it - calling GetClassName
works in constructors by the virtue of typeid - but you won't be able to
create deep hierarchies this way.
----------
#include <iostream>
#include <list>
#include <typeinfo>
struct Root
{
virtual const char * GetClassName() const = 0;
};
template <class T> class Base : public Root
{
public:
Base()
{
std::cout << "I'm " << GetClassName() << std::endl;
}
virtual const char * GetClassName() const
{
return typeid(T).name();
}
};
class Child : public Base<Child>
{
};
class AnotherChild :public Base<AnotherChild>
{
};
// oops, GetClassName will return AnotherChild
class GrandChild : public AnotherChild
{
};
int main()
{
using std::list;
list<Root *> items;
items.push_back(new Child);
items.push_back(new AnotherChild);
items.push_back(new GrandChild);
for (list<Root *>::iterator i = items.begin(); i != items.end(); ++i)
{
std::cout << (*i)->GetClassName() << std::endl;
delete *i;
}
return 0;
}
-----------
I'm class Child
I'm class AnotherChild
I'm class AnotherChild
class Child
class AnotherChild
class AnotherChild
-----------
-- slimb
---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html
- References:
- [gameprogrammer] test
- From: Dave Slutzkin
- [gameprogrammer] Re: test
- From: David Olofson
- [gameprogrammer] Re: test
- From: Dave Slutzkin
- [gameprogrammer] Pure virtual function getting called
- From: Kevin Jenkins
Other related posts:
- » [gameprogrammer] Pure virtual function getting called
- » [gameprogrammer] Re: Pure virtual function getting called
- » [gameprogrammer] Re: Pure virtual function getting called
- » [gameprogrammer] Re: Pure virtual function getting called
- » [gameprogrammer] Re: Pure virtual function getting called
- » [gameprogrammer] Re: Pure virtual function getting called
- » [gameprogrammer] Re: Pure virtual function getting called
- » [gameprogrammer] Re: Pure virtual function getting called
- » [gameprogrammer] Re: Pure virtual function getting called
- [gameprogrammer] test
- From: Dave Slutzkin
- [gameprogrammer] Re: test
- From: David Olofson
- [gameprogrammer] Re: test
- From: Dave Slutzkin
- [gameprogrammer] Pure virtual function getting called
- From: Kevin Jenkins