top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is Virtual functions in c++?

0 votes
374 views
What is Virtual functions in c++?
posted Jul 27, 2017 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Class which contains virtual functions are called abstract classes.Virtual fuctions have same name and are declared in, base class and also 'n' number of derived classes.

'Virtual' is a keyword preceded before any fuction to make it as a virtual function.

Virtual function equated to 0 is called ' pure virtual function' .

Class shape

{ 
public:

Virtual void area()=0;

};

Class shape : public rectangle , public triangle ;

Here class ' shape ' is base class.Where as rectangle and triangle are derived classes.

So, area is a virtual function that are redefined in derived classes.

  class rectangle

    {

   Public:

   Void area()
  {
    area=base * height ;

    Cout<<area <<endl ;
     }  
  };

    Class triangle

    {

    Public:

    Void area() 
         { 
     area= (base*height) /2;

     Cout<<area<<endl;
         }
     };

In the above example both classes have the function named area.

Rectangle rect.area(); will refer to the function redefined in class rectangle.

Triangle tri.area(); will refer to the function redefined in class triangle.

Hence , this is only possible when you have declared area () in base class as 'virtual'.

answer Jul 28, 2017 by Sulekha Kumari
Similar Questions
+2 votes

When a function is declared as virtual and when a class ? Please explain with examples.

0 votes

What is a pure virtual destructor in C++? What is its need, advantage and disadvantage, please explain with example?

...