What is a pure virtual function?--什么是纯虚函数

转载自:http://www.research.att.com/~bs/bs_faq2.html#pure-virtual

(Bjarne Stroustrup's C++ Style and Technique FAQ)

What is a pure virtual function?

A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be "pure" using the curious "=0" syntax. For example:
	class Base {
public:
void f1(); // not virtual
virtual void f2(); // virtual, not pure
virtual void f3() = 0; // pure virtual
};

Base b; // error: pure virtual f3 not overridden
Here, Base is an abstract class (because it has a pure virtual function), so no objects of class Base can be directly created: Base is (explicitly) meant to be a base class. For example:
	class Derived : public Base {
// no f1: fine
// no f2: fine, we inherit Base::f2
void f3();
};

Derived d; // ok: Derived::f3 overrides Base::f3
Abstract classes are immensely useful for defining interfaces. In fact, a class with only pure virtual functions is often called an interface.

You can define a pure virtual function:

	Base::f3() { /* ... */ }
This is very occasionally useful (to provide some simple common implementation detail for derived classes), but Base::f3() must still be overridden in some derived class.

If you don't override a pure virtual function in a derived class, that derived class becomes abstract:

	class D2 : public Base {
// no f1: fine
// no f2: fine, we inherit Base::f2
// no f3: fine, but D2 is therefore still abstract
};

D2 d; // error: pure virtual Base::f3 not overridden
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值