[gameprogrammer] Re: Pure virtual function getting called

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


Other related posts: