c++(cplusplus)-virtual-functions

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.



VIRTUAL FUNCTION:

class Base

{

public:

virtual void create()

{

cout<<"Base Class" ;

}

};

class Derived : public Base

{

public:

void display()

{

cout<<"Derived class";

}

};

void main()

{

Base *p,*q;

p = new Base();

p ->display();

y= new Derived();

y ->display();

}

The output of the program is: Base Class

Derived Class

As we had declared the function to be virtual, so run-time linking occurs and the derived class function is being invoked the second time.Otherwise if the function had not been declared virtual then both time base class function would have been called because the function address is statically bound during compile time in this case.


Virtual Constructors and Destructors

A constructor cannot be virtual because its virtual table would not be available in the memory when the constructor is invoked.

Destructors are called in the reverse order of inheritance. A virtual destructor is one that is declared as virtual in the base class and is used to ensure that destructors are called in the correct order. If a base class pointer points to a derived class object and later we use delete operator to delete the object, then the destructor of derived class  is not called.

#include <iostream.h>
class base
{
       public:
       ~base()
        {

        }
};

class derived : public base
{
        public:
        ~derived()
        {

        }
};

void main()
{
         base *ptr = new derived();
         delete ptr;
}

In this case the pointer is of type base, the base class destructor would be called but the derived class destructor would not be called even once. Hence MEMORY LEAK occurs.To avoid this, the destructor is made virtual in the base class as in the example shown below:

#include <iostream.h>
class base
{
public:
virtual ~base()
{

}
};

class derived : public base
{
public:
~derived()
{

}

};

void main()
{

base *ptr = new derived();
delete ptr;
}





-4 points
vipuljhamnani's picture
Created by vipuljhamnani
1 point

i think "virtual void create()" must be "virtual void display()", may be its a typo

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.