分享

Restrictions on Using Abstract Classes

 windycityboy 2013-09-11

Abstract classes cannot be used for:

  • Variables or member data

  • Argument types

  • Function return types

  • Types of explicit conversions

Another restriction is that if the constructor for an abstract class calls a pure virtual function, either directly or indirectly, the result is undefined. However, constructors and destructors for abstract classes can call other member functions.

Pure virtual functions can be defined for abstract classes, but they can be called directly only by using the syntax:

abstract-class-name :: function-name( )

This helps when designing class hierarchies whose base class(es) include pure virtual destructors, because base class destructors are always called in the process of destroying an object. Consider the following example:

// Declare an abstract base class with a pure virtual destructor.
// deriv_RestrictionsonUsingAbstractClasses.cpp
class base {
public:
    base() {}
    virtual ~base()=0;
};

// Provide a definition for destructor.
base::~base() {}

class derived:public base {
public:
    derived() {}
    ~derived(){}
};

int main() {
    derived *pDerived = new derived;
    delete pDerived;
}

When the object pointed to by pDerived is deleted, the destructor for class derived is called and then the destructor for class base is called. The empty implementation for the pure virtual function ensures that at least some implementation exists for the function.

NoteNote:

In the preceding example, the pure virtual function base::~base is called implicitly from derived::~derived. It is also possible to call pure virtual functions explicitly using a fully qualified member-function name.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多