Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Need of Virtual functions in C++

ajay4ajay4 Member Posts: 14
What is the need of virtual functions in C++ rather than c?
My knowledge about it is that it is used to add(i mean redefining in derived class) more facility to that function. Is it True?Otherwise please explain me.

Comments

  • weiccoweicco Member Posts: 950
    : What is the need of virtual functions in C++ rather than c?
    : My knowledge about it is that it is used to add(i mean redefining in derived class) more facility to that function. Is it True?Otherwise please explain me.
    :

    A little example:

    [code]
    class Class {
    public:
    virtual ~Class() { /* do something important */ }
    };

    class CCustomClass : public Class {
    public:
    ~CCustomClass() { /* do something */ }
    }
    [/code]

    If Class::~Class wasn't declared as virtual, it wouldn't be called when destroying CCustomClass-object. Now when it is virtual, CCustomClass::~CCustomClass gets called first, Class::~Class after that.

    Second example:

    [code]
    class CCallback {
    public:
    virtual void cbfunc() { /* do something */ }
    };

    class CCustomCallback : public CCallback {
    public:
    void cbfunc() { /* do something usefull and call parent */
    CCallback::cbfunc();
    }
    };

    class CSomeClass {
    public:
    static void doSomethingAsynchronously(CCallback& cb) {
    /* do something, then call: */
    cb.cbfunc();
    }
    };

    CCustomCallback cb;
    CSomeClass::doSomethingAsynchronously(cb);
    [/code]

    If CCallback::cbfunc wouldn't be virtual, doSomethingAsynchronously would call CCallback::cbfunc and not CCustomCallback::cbfunc which I wanted it to call.

    Then there is pure virtual. If I would have declared CCallback like this:

    [code]
    class CCallback {
    public:
    virtual void cbfunc() = 0;
    };
    [/code]

    Every class that derives CCallback would now HAVE to implement cbfunc-method and CCustomCallbac::cbfunc can't call parent's cbfunc-method.
  • ash1894ash1894 Member Posts: 26
    Hi,
    You r quite right. I believe you know about run time polymorphism which is a very powerful concept of c++. Virtual function will help you to do that. If you have anything to ask more you can ask me.
    ------------------->ASH
    : What is the need of virtual functions in C++ rather than c?
    : My knowledge about it is that it is used to add(i mean redefining in derived class) more facility to that function. Is it True?Otherwise please explain me.
    :

  • riyajose123riyajose123 Member Posts: 1
    hello if you want to know the use if virtual function visit :www.geocities.com/riyajose123

    And click the C++ link

    Thank you Riya jose BCA
Sign In or Register to comment.