-1

I understood what is virtual function and pure virtual function but, what is the use of virtual function in C++. Can I get a more apt example for this concept in which virtual function can be used?

The example given for this is 1.Shape a base class 2.Rectangle and square be the derived class

My question is what is the need for shape derived class in first place? Why cant we directly uses rectangle and square class directly

samnaction
  • 1,194
  • 1
  • 17
  • 45
  • this might help http://stackoverflow.com/questions/2391679/can-someone-explain-c-virtual-methods?rq=1 – Tim Feb 26 '14 at 10:08
  • 1
    Please don't misuse standard terminology. 'Real time' has a very specific meaning in IT, and that isn't it. What you mean is something like 'real-world'. You need to look up 'polymorphism', which is one of the pillars of OOP. – user207421 Feb 26 '14 at 10:10
  • Parsing a diverse set of application messages from the network? – Kerrek SB Feb 26 '14 at 10:11

2 Answers2

0

You can use virtual functions when you want to override a certain behavior(read method) for your derived class than the one implemented for the Base class and you want to do so at run-time through an pointer to Base class.

Example:

#include <iostream>
using namespace std;

class Base {
public:
   virtual void NameOf();   // Virtual function.
   void InvokingClass();   // Nonvirtual function.
};

// Implement the two functions.
void Base::NameOf() {
   cout << "Base::NameOf\n";
}

void Base::InvokingClass() {
   cout << "Invoked by Base\n";
}

class Derived : public Base {
public:
   void NameOf();   // Virtual function.
   void InvokingClass();   // Nonvirtual function.
};

// Implement the two functions.
void Derived::NameOf() {
   cout << "Derived::NameOf\n";
}

void Derived::InvokingClass() {
   cout << "Invoked by Derived\n";
}

int main() {
   // Declare an object of type Derived.
   Derived aDerived;

   // Declare two pointers, one of type Derived * and the other
   //  of type Base *, and initialize them to point to aDerived.
   Derived *pDerived = &aDerived;
   Base    *pBase    = &aDerived;

   // Call the functions.
   pBase->NameOf();           // Call virtual function.
   pBase->InvokingClass();    // Call nonvirtual function.
   pDerived->NameOf();        // Call virtual function.
   pDerived->InvokingClass(); // Call nonvirtual function.
}

Output will be:

Derived::NameOf
Invoked by Base
Derived::NameOf
Invoked by Derived
Raging Bull
  • 18,593
  • 13
  • 50
  • 55
0

You can use virtual function to achieve runtime polymorphism.

rajenpandit
  • 1,265
  • 1
  • 15
  • 21