Manufacturing abstract base class--C + + must know and clause 33

Source: Internet
Author: User

Abstract class, a class that contains pure virtual functions, is not allowed to create objects.

However, sometimes we don't need a function defined as a pure virtual function, but we still want this class to be like an abstract class, not to create objects.

Method 1: Simulate the nature of the abstract base class by ensuring that there are no common constructors in the class. means that we must declare at least one constructor and one copy constructor to prevent the compiler from implicitly public-inline constructors. Declared as protected, which allows the constructors of derived classes to use them while blocking the creation of objects.

class abc{protected:        ABC ();        ABC (const abc&);};

Method 2: The way to make a class an abstract base class requires artificially making a virtual function as pure virtual. Destructors are usually the best candidates.

class abc{protected:       virtual ~ ABC () =0; };

Note that in this example, it is necessary to provide an implementation for the pure virtual function, because the destructor of the derived class will implicitly call the destructor of the base class (note that implicit invocation of a base class destructor from within a derived class destructor is always non-virtual)

Method 3: Use a protected, non-virtual destructor. Used when a class does not have any virtual functions and does not need to display the declaration constructor.

class abc{protected:       ~ ABC ();}; // ... ABC * ABC; // no error . ABC * cba=new// will not error delete p; // Error! destructor protected // Error! An implicit call to the destructor of ABC

Manufacturing abstract base class--C + + must know and clause 33

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.