Pure Virtual Function, Abstract Class and Interface in C++

注: 此为英文笔记,如需翻译请私信或留评论

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:

  1. We can have pointers and references of abstract class type.
  2. If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.
  3. 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值