Last updated:2026-10-12
C++ Pure Virtual Functions and Abstract Classes¶
About the Author¶
WeChat official account:

1. Pure Virtual Functions and Abstract Classes¶
A pure virtual function (or abstract function) in C++ is a virtual function that we do not implement! We only declare it! A pure virtual function is declared by assigning 0 in its declaration!
- Pure virtual function: a virtual function without a function body
- Abstract class: a class that contains a pure virtual function
An abstract class can only be used as a base class to derive new classes; you cannot create objects of an abstract class. Pointers and references of an abstract class -> objects of classes derived from that abstract class!
Code examples: abstract_base.h, pure_virtual.cpp
2. Implementing an Abstract Class¶
Inside an abstract class: a pure virtual function may be called from within a member function, but pure virtual functions cannot be used inside constructors/destructors.
If a class is derived from an abstract class, it must implement all the pure virtual functions of the base class before it becomes a non-abstract class.
// A为抽象类
class A {
public:
virtual void f() = 0; // 纯虚函数
void g(){ this->f(); }
A(){} // 构造函数
};
class B : public A{
public:
void f(){ cout<<"B:f()"<<endl;} // 实现了抽象类的纯虚函数
};
Code example: abstract.cpp
3. Important Points¶
-
Constructors cannot be virtual, while destructors can be virtual destructors
// 抽象类 class Base { public: Base(){ cout << "Constructor: Base" << endl; } virtual ~Base(){ cout << "Destructor : Base" << endl; } virtual void func() = 0; }; class Derived: public Base { public: Derived(){ cout << "Constructor: Derived" << endl; } ~Derived(){ cout << "Destructor : Derived" << endl;} void func(){cout << "In Derived.func()." << endl;} };When a base class pointer points to a derived class object and the object is deleted, we may want the appropriate destructor to be called. If the destructor is not virtual, only the base class destructor gets called.
4. Complete Example¶
An abstract class is inherited and implemented by its derived classes!
Code example: derived_full.cpp
Related Topics¶
- C++ assert | C++那些事
- C++ Bit Fields | C++那些事
- Implementing C++ Polymorphism in C | C++那些事
- C++ const Constants and Qualifiers | C++那些事
- The Complete C++ const Family | C++那些事
- C++ Dereference Operator * | C++那些事
- C++ Initialization and Assignment | C++那些事
- Ways to Return Multiple Values in C++ | C++那些事
- C++ mutable Keyword | C++那些事
- C++ restrict and Compiler Optimization | C++那些事