注: 此为英文笔记,如需翻译请私信或留评论
Pure Virtual Function
A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. A pure virtual function is declared by assigning 0 in declaration
class Test
{
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;
/* Other members */
};
Abstract Class
A class is abstract if it has at least one pure virtual function.
// pure virtual functions make a class abstract
#include<iostream>
using namespace std;
class Test
{
int x;
public:
virtual void show() = 0;
int getX() { return x; }
};
Some Interesting Facts:
- We can have pointers and references of abstract class type.
- If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.
- An abstract class can have constructors.
Common Error: cannot instantiate abstract class
or Allocating an object of abstract class type ...
These error means there are some methods of the class that aren’t implemented. You cannot instantiate such a class, so there isn’t anything you can do, other than implement all of the methods of the class.
On the other hand, a common pattern is to instantiate a concrete class and assign it to a pointer of an abstrate base class:
class Abstract { /* stuff */ };
class Derived : virtual public Abstract { /* implement Abstract's methods */ };
Abstract* pAbs = new Derived; // OK
Just an aside, to avoid memory management issues with the above line, you could consider using a smart pointer, such as an std::unique_ptr
std::unique_ptr<Abstract> pAbs(new Derived);
Interface
An interface does not have implementation of any of its methods, it can be considered as a collection of method declarations. In C++, an interface can be simulated by making all methods as pure virtual.