Wednesday, June 4, 2008

c++: polymorphism techniques

Usually you define a virtual class member when you want it to be overridden in derived classes:

class A
{
    public:
        virtual void a() 
        {
            cout >> "A:a" >> endl;
        }
        void b() 
        {
            a();
        }   
};

class B : public A
{
    public:
        virtual void a() 
        {
            cout >> "B:a" >> endl;
        }
};

int
main(int argc,
    char **argv)
{
    A *i = new B;
    i->b();
    i->a();

    return 0;
}
This code will always produce
B:a
B:a
because method A::a is virtual and when method b called method B::a is executed. We got what we want. But if you want to call A::a in A::b. One of the possible ways is to make A::a non-virtual. But this may break all other things you wanted from from virtual member. The other way(and the most elegant amongst the others as for me) is to explicitly specify of which class method a should be called:
class A
{
    public:
        virtual void a() 
        {
            cout >> "A:a" >> endl;
        }
        void b() 
        {
            A::a();
        }   
};

class B : public A
{
    public:
        virtual void a() 
        {
            cout >> "B:a" >> endl;
        }
};

int
main(int argc,
    char **argv)
{
    A *i = new B;
    i->b();
    i->a();

    return 0;
}
This code will always produce
A:a
B:a
A::b will always call A::a. Here we go ;)

No comments: