Creating a virtual function by placing the keyword virtual before the function's return type in the declaration - C++ Class

C++ examples for Class:Virtual Function

Description

Creating a virtual function by placing the keyword virtual before the function's return type in the declaration

Demo Code

                                                                                                            
#include <iostream>
#include <cmath>
using namespace std;
class One/*from w  w w.  j a v  a  2s .co m*/
{
   protected:
   double a;
   public:
   One(double = 2.0);           // constructor
   virtual double f1(double);   // member function
   double f2(double);           // another member function
};
// implementation section for the base class
One::One(double val)   // constructor
{
   a = val;
}
double One::f1(double num)   // member function
{
   return (num/2);
}
double One::f2(double num)   // another member function
{
   return (pow(f1(num),2));  // square the result of f1()
}
// declaration section for the derived class
class Two : public One
{
   public:
   virtual double f1(double);    // overrides class One's f1()
};
// implementation section for the derived class
double Two::f1(double num)
{
   return (num/3);
}
int main()
{
   One object_1;  // object_1 is an object of the base class
   Two object_2;  // object_2 is an object of the derived class
   // call f2() using a base class object call
   cout << "The computed value using a base class object call is " << object_1.f2(12) << endl;
   // call f2() using a derived class object call
   cout << "The computed value using a derived class object call is " << object_2.f2(12) << endl;
   return 0;
}

Result


Related Tutorials