关闭

What is a pure virtual function?

标签: classfunctionc++
669人阅读 评论(0) 收藏 举报
分类:

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
 
转载自:http://www.research.att.com/~bs/bs_faq2.html#pure-virtual
                之 
Bjarne Stroustrup's C++ Style and Technique FAQ
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1488372次
    • 积分:14070
    • 等级:
    • 排名:第874名
    • 原创:166篇
    • 转载:381篇
    • 译文:16篇
    • 评论:143条
    文章分类