0

Possible Duplicate:
C++ Virtual/Pure Virtual Explained

what is the exact difference b/w virtual function and pure virtual function and where should we use these functions in which situation?

Community
  • 1
  • 1
ankit
  • 877
  • 3
  • 9
  • 14

2 Answers2

2

A pure virtual function is one that is declared like this:

class Foo {
    virtual void bar() = 0;
};

bar is a pure virtual member of Foo. It has no implementation (hence = 0), and cannot be called. Any class that inherits from Foo must provide an implementation for bar. That is the only difference: The parent class has no implementation for the pure virtual, so derived classes must provide it. (There's an exception to this, but it's rarely used.)

Otherwise, it works exactly the same way. Given:

class Baz : public Foo {
    virtual void bar() {}
};

Any instance of Baz can be accessed with a pointer of type Foo* and Baz::bar will be called. If Foo::bar is pure virtual, then Foo cannot be instantiated, and calls to Foo::bar will be errors. If Foo::bar is not pure, then the implementation provided for Foo::bar will be called for instances of Foo and Baz::bar will be called for instances of Baz, even if it's through a Foo*.

(Pure virtuals can also have implementations so that, for example, Baz::bar can call Foo::bar, but this is uncommon.)

greyfade
  • 24,948
  • 7
  • 64
  • 80
0
  1. Virtual Function have a function body.

  2. Overloaded can be done by the Vartual Function.

  3. It is define as: Virtual int runFun();

while

  1. Pure Vartual Function have on function body.

  2. Overloaded is must in Pure Vartual function.

  3. It is define as: Virtual int runFun()=0;

ratty
  • 13,216
  • 29
  • 75
  • 108