C++ implements class instance analysis that cannot be inherited

  • 2020-04-02 02:35:54
  • OfStack

The example of this paper shows the method of C++ to implement the class that cannot be inherited. The specific implementation method is as follows:

Method one:


#include <iostream>

using namespace std;

class A
{
public:
  static A* getInstance();
  static void deleteInstance(A* pA);

private:
  A() { cout << "construct An";}
  ~A() { cout << "destruct An"; }
};

A* A::getInstance()
{
  return new A;
}

void A::deleteInstance(A* pA)
{
  delete pA;
  pA = nullptr;
}

int main()
{
  A* pA = A::getInstance();
  A::deleteInstance(pA);
  cin.get();
}

This method is essentially a constructor, destructor private, so when you want to derive a class, derived classes can't construct a parent class, so it won't work.

Method 2:


#include <iostream>

using namespace std;

template <typename T>
class A
{
  friend T;
private:
  A(int data) : m_data(data) { cout << "construct A. data: " << m_data << endl; }
  ~A() {}

  int m_data;
};

class B : virtual public A<B>
{
public:
  B(int data) : A(data) { cout << "construct Bn"; }
  ~B() {}
};


int main(void)
{
  B b(4);
  cin.get();
}

Class B is set to be A friend of class A, so class B can be A subclass of A to construct A parent class. By this time the class B can be normal use, but cannot be derived from the class B A subclass, because virtual inheritance. A, B if you want to class C: pulic B, because it is virtual inheritance, so in the C class constructor is directly invoke A constructor of A class, but B is A friend, not C, so can't directly call A constructor, A compiler error. Here the C class must call the constructor of A directly

But if you change the declaration of class B to class B: public A < B > Then you can derive A subclass C from class B, because without virtual inheritance, the constructor of class C calls the constructor of class B, and the constructor of class B calls the constructor of class A (B is A friend of A, even if the constructor of A is private). This is called layer upon layer up.

I believe that through this example can help you better understand the principle and use of C++ classes.


Related articles: