Wednesday, September 7, 2011

prog: Virtual function

http://www.cplusplus.com/forum/beginner/13885/




A function should be declared virtual [in the base class] if you ever intend to allow derived classes to reimplement the function AND you intend to call the function through a base class pointer/reference.



struct Base
{
    virtual void do_something() = 0;
};


struct Derived1 : public Base
{
    void do_something()
    {
         cout << "I'm doing something";
    }
};

struct Derived2 : public Base
{
    void do_something()
    {
         cout << "I'm doing something else";
    }
};

int main()
{
    Base *pBase = new Derived1;
    pBase->do_something();//does something
    delete pBase;
    pBase = new Derived2;
    pBase->do_something();//does something else
    delete pBase;
    return 0;
}

No comments:

Post a Comment