Details and simple examples of C++ virtual functions

  • 2020-05-26 09:40:49
  • OfStack

Details of C++ virtual functions

The use of virtual functions and the use of pure virtual functions.

Virtual functions are defined in the base class, and then subclass overrides the function, the pointer of the base class points to the object of the subclass, can call this function, and this function retains the subclass overrides the function.

Pure virtual functions are not defined in the base class, just need to declare it, and then because it is a pure virtual function, is not able to generate the object of the base class, but can generate a pointer to the base class.

The main difference between pure virtual functions and virtual functions is that the base class of pure virtual functions cannot produce objects, while the base class of virtual functions can produce objects.


// pointers to base class 
#include <iostream> 
using namespace std; 
class Polygon { 
 protected: 
  int width, height; 
 public: 
  void set_values (int a, int b) 
   { width=a; height=b; } 
  virtual int area(){ 
    return 0; 
  } 
}; 
 
class Rectangle: public Polygon { 
 public: 
  int area() 
   { return width*height; } 
}; 
 
class Triangle: public Polygon { 
 public: 
  int area() 
   { return width*height/2; } 
}; 
 
int main(){ 
  Polygon *p1,*p2; 
  Rectangle rec; 
  Triangle tri; 
  p1 = &rec; 
  p2 = &tri; 
  p1->set_values(1,2); 
  p2->set_values(2,4); 
  cout << rec.area() << endl; 
  cout << tri.area() << endl; 
  cout << p1->area() << endl; 
  cout << p2->area() << endl; 
  return 0; 
} 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: