The constructor is defined as the benefit of private or protected

  • 2020-04-02 01:46:36
  • OfStack

Declare constructors, destructors private and protected. How are objects created? You can't call the constructor from the outside anymore, but the object has to be constructed, so how do you do that? By asking this question, you've given c++ some thought.

Syntactically, if a function is declared protected or private, it cannot be called directly from the outside.
For protected functions, other "internal" functions of the subclass can be called.
In the case of private, it can only be called by other functions "inside" the class.

That's what the grammar says, and you know it.
So why do you sometimes declare a constructor or destructor as protected or private?

The commonly used scenario is as follows:
1. If you don't want the outside user to construct the object of A class (assuming the name of the class is A) and you want the user to construct only subclasses of class A, you can declare the constructor/destructor of class A as protected and the constructor/destructor of class A's subclass as public. Such as:


class A
{ protected: A(){}
  public: ....
};
calss B : public A
{ public: B(){}
  ....
};
A a; // error
B b; // ok

2. If the constructor/destructor is declared private, only the "internal" functions of the class can construct the class object. I don't know if you understand the "inside" here, but here's an example.

class A
{
private:
    A(){  }
    ~A(){ }
public:
    void Instance()//A function inside of class A
    {
        A a;
    }
};

The above code can be compiled. The Instance function in the above code is an inner function of class A. The body of the Instance function builds an object of A.

However, the Instance function cannot be called from the outside. Why?

To call the Instance function, an object must be constructed. But the constructor is declared private. An object cannot be constructed directly from the outside.
A aObj; // it won't compile
AObj. The Instance ();
However, if Instance is a static function, it can be called without going through an object. As follows:


class A
{
private:
    A():data(10){ cout << "A" << endl; }
    ~A(){ cout << "~A" << endl; }
    public:
    static A& Instance()
    {
        static A a;
        return a;
    }
    void Print()
    {
        cout << data << endl;
    }
private:
    int data;
};
A& ra = A::Instance();
ra.Print();

The above code is actually a simple C++ code implementation of the design pattern singleton pattern.

There is another case where the copy constructor and operator=(assignment operator overload) are normally declared private, but there is no implementation body.
The purpose of this is to prohibit external users of a class from copying objects of that class.
Please refer to clause 27 in effective C++ for details.


Related articles: