The difference between virtual functions and pure virtual functions: 1. Pure virtual functions only have definitions and no implementation; virtual functions have both definitions and implementation codes. 2. A class containing pure virtual functions cannot define its objects, but a class containing virtual functions can.
Related recommendations: "C Video Tutorial"
Virtual function (impure virtual)
The main function of C's virtual function is "runtime polymorphism". The parent class provides the implementation of the virtual function and provides the default function implementation for the subclass.
Subclasses can override the virtual functions of the parent class to achieve specialization of the subclass.
The following is a virtual function in a parent class:
class A { public: virtual void ss() { cout<<"我是基类的虚函数"<<endl; } };
Pure virtual function
A class in C that contains a pure virtual function is called It is an "abstract class". Abstract classes cannot use new to create objects. Only subclasses that implement this pure virtual function can create new objects.
The pure virtual function in C is more like "only providing declarations, no implementation". It is a constraint on subclasses and "interface inheritance".
Pure virtual functions in C are also a kind of "runtime polymorphism".
If the following class contains pure virtual functions, it is an "abstract class":
class A { public: virtual void out1(string s)=0; //我是基类的虚函数 };
For example
#include<iostream> #include<string> #include<cstring> #include<cstdlib> #include<algorithm> using namespace std; class a { private: public: a(){ //构造函数用内联函数的形式 } //虚函数 virtual void xhs(){ //这个虚函数必须得在基类中实现 cout<<"我是基类的虚函数"<<endl;//即使是空的虚函数也要在基类中实现 } //派生类中可以不写这个函数,但是派生类对象调用时会调用积累的虚函数 //纯虚函数 virtual void cxhs() =0; //这个纯虚函数不在基类中实现,必须在子类中实现 }; class b:public a { private: public: void xhs(){ //这个是可有可无的 cout<<"我是派生类覆盖基类虚函数的函数"<<endl; } //* //* void cxhs(){ //这个是必须有实现的 cout<<"我是派生类覆盖基类虚函数的函数"<<endl; } //* //* }; //* //* int main() //* //* { //* //* b c; //* //* c.xhs(); //* //调用派生类的 c.cxhs();//调用派生类的 }
Virtual functions and pure virtual functions The difference
1) Pure virtual functions only have definitions and no implementation; while virtual functions have both definitions and implementation codes.
Pure virtual functions generally do not have a code implementation part, such as virtual void print() = 0; 2)
General virtual functions must have a code implementation part, otherwise the function will be undefined mistake.
2) A class containing pure virtual functions cannot define its objects, but a class containing virtual functions can.
The above is the detailed content of What is the difference between virtual function and pure virtual function?. For more information, please follow other related articles on the PHP Chinese website!