views:

497

answers:

5

Possible Duplicate:
C++ Virtual/Pure Virtual Explained

Hi,

Need to know what is the difference between a pure virtual function and a virtual function?

I know "Pure Virtual Function is a Virtual function with no body" but what does this mean and what is actually done by the line below

virtual void virtualfunctioname() = 0

A: 

A pure virtual function has 0 "assigned to it" and has no definition.

virtual int SomeFunction() = 0;
Daniel A. White
A: 

A pure virtual function is usually not (but can be) implemented in a base class and must be implemented in a leaf subclass.

You denote that fact by appending the "= 0" to the declaration, like this:

class AbstractBase
{
    virtual void PureVirtualFunction() = 0;
}

Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:

class Derived : public AbstractBase
{
    virtual void PureVirtualFunction() { }
}
Johann Gerell
In C++, a pure virtual function can be implemented.
sbi
yes, and for the pure virtual destructor, it must be implemented.
daramarak
@daramarak: pure virtual constructor ? in C++?
Naveen
@Naveen: http://stackoverflow.com/questions/2609299/2609404#2609404
sbi
@sbi: I read at is constructor instead of destructor. My mistake..
Naveen
@Naveen: Min e, too. I read yours as "destructor"...
sbi
+3  A: 

A virtual function makes its class a polymorphic base class. Derived classes can override virtual functions. Virtual functions called through base class pointers/references will be resolved at run-time. That is, the dynamic type of the object is used instead of its static type:

 Derived d;
 Base& rb = d;
 // if Base::f() is virtual and Derived overrides it, Derived::f() will be called
 rb.f();  

A pure virtual function is a virtual function whose declaration ends in =0:

class Base {
  // ...
  virtual void f() = 0;
  // ...

A pure virtual function makes the class it is defined for abstract. Abstract classes cannot be instantiated. Derived classes need to override/implement all inherited pure virtual functions on order to not to be abstract.
In C++, a class can define a pure virtual function that has an implementation. (What that's good for is debatable.)

sbi
A: 

For a virtual function you need to provide implementation in the base class. However derived class can override this implementation with its own implementation. Normally , for pure virtual functions implementation is not provided. You can make a function pure virtual with =0 at the end of function declaration. Also, a class containing a pure virtual function is abstract i.e. you can not create a object of this class.

Naveen
A: 

You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.

AshleysBrain