Ban class inheritance in C ++

Source: Internet
Author: User

Http://blog.csdn.net/wufanglove/

The following code disables inheritance:

Class;

Class lock {
Friend Class;
PRIVATE:
Lock (){}
};

Class A: virtual public lock {
//...
Public:
A ()
{}
A (int t)
{}

};

Now, if you try to generate other classes from Class A, you will get compilation errors similar to the following.

Class B: public
{}; // Lock: lock': cannot access private member declared in class 'lock'

This is because all the derived classes need to call the constructor of the virtual base class. Therefore, B generated from arequires to call the constructor of the virtual base class (that is, lock ).

And the lock constructor is private, and Class B is not the friends of the lock, so this will generate a compilation error.
If we remove the virtual keyword when class A is generated, the program will be compiled successfully. This is because in non-virtual inheritance, any class can

Call the constructor in the parent class. Therefore, in non-virtual inheritance, B will call its direct parent class A constructor and a will call its direct parent class

The constructor of the class lock is valid.

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.