Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

16 virtual function

1,390 views

Published on

16 virtual function

Published in: Technology, Real Estate
  • Be the first to comment

16 virtual function

  1. 1. Virtual Functions 09/04/131 VIT - SCSE By G.SasiKumar., M.E., (Ph.D)., Assistant Professor School of Computing Science and Engineering VIT University
  2. 2. 09/04/132 VIT - SCSE Virtual Functions  C++ matches a function call with the correct function definition at compile time − known as static binding  the compiler can match a function call with the correct function definition at run time − known as dynamic binding. − declare a function with the keyword virtual if you want the compiler to use dynamic binding for that specific function.
  3. 3. 09/04/133 VIT - SCSE Virtual Functions  The virtual keyword indicates to the compiler that − it should choose the appropriate definition of a function not by the type of reference, but by the type of object that the reference refers to.
  4. 4. 09/04/134 VIT - SCSE Virtual Methods  Therefore, − a virtual function is a member function you may redefine for other derived classes, − can ensure that the compiler will call the redefined virtual function for an object of the corresponding derived class, − even if you call that function with a pointer or reference to a base class of the object.  A class that declares or inherits a virtual function is called a polymorphic class.
  5. 5. Declaring virtual  prefix declaration with the virtual keyword  redefine a virtual member function in any derived class  this is called overriding − understand the contrast with overloading For example, the general syntax to declare a Virtual Function uses: class classname //This denotes the base class of C++ virtual function { public: virtual void memberfunctionname() //This denotes the C++ virtual function { ............. ............ } };
  6. 6. More on definition  overridden function must have same name and same parameter list − no need to use the virtual keyword again − return type can be different  if the parameter lists are different, they are considered different − in this case, it is not overridden, but hidden − hidden methods cannot be called
  7. 7. Example  class Vehicle   //This denotes the base class of  C++ virtual function {  public:  virtual void Make()   //This denotes the C++  virtual function {  cout <<"Member function of Base Class Vehicle  Accessed"<<endl;  }  }; class FourWheeler : public Vehicle  {  public:  void Make()  {  cout<<"Virtual Member function of Derived class  FourWheeler Accessed"<<endl;  }    }; void main()  {  Vehicle *a, *b;  a = new Vehicle();  a->Make();  b = new FourWheeler();  b->Make();  } 

×