Implement a class that cannot be inherited in C + +

Source: Internet
Author: User

Constructors are the key to implementing inheritance, when a subclass object is constructed, the constructor of the parent class is called first, and its own constructor is called.

#include <iostream>using namespace std;template <typename t>class a{public    :        friend T;    Private:        A () {}        ~a () {}};class b:virtual public A <b>{public    :        B () {}        ~b () {}};//class C: Virtual public b//{//  public://      C () {}//      ~c () {}//};int main () {    B b;//  c C;

Define a friend class friend T,b in the inheritance, with their own to materialize a, set themselves to a friend class, so that you can access A's private function (constructor), B can normally define the object B,c virtual inheritance B, but the friend relationship can not inherit. So c cannot call A's constructor at construction time, and if you open the comment section, the error below will be reported.

Template.cpp:In constructor ' C::c () ':
Template.cpp:11:3: Error: ' A<t>::a () [With T = B] ' is private
A () {}
^
Template.cpp:25:6: Error:within This context
C () {}
^
Template.cpp:12:3: Error: ' A<t>::~a () [With T = B] ' is private
~a () {}
^
Template.cpp:25:6: Error:within This context
C () {}
^
Template.cpp:In destructor ' c::~c () ':
Template.cpp:12:3: Error: ' A<t>::~a () [With T = B] ' is private
~a () {}
^
Template.cpp:26:7: Error:within This context
~c () {}
^

Implement a class that cannot be inherited in C + +

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.