Friday, August 25, 2017

Making Private the Default Constructor

In C++ you should make private the default constructor, copy constructor, and operator=.

Prevent application code from using any special functions supported automatically by the C++ compiler but not supported specifically by a class.  Make private within a class any of these special functions if you do not plan to use them within the application code and you do not define them:
  1. default constructor, 
  2. copy constructor, and 
  3. assignment operator.  

Declare them private in the dot h file if you do not define them. Here is an example.
class A {
public:
                A( int n);  // specialized constructor
                int getNum( );  // “getter” function
private:
                int i_;
                A( );     // default constructor made private (disabled)
                A( A& ); // copy constructor made private (disabled)
                A& operator=(const A&);  // assignment operator made private (disabled)
};

You might be surprised when you make them private that inaccurate coding might throw a compiler error saying you have just tried to use a private function.   There are times you invoke them in your code without intending to invoke them.  The compiler will invoke a "factory supplied" version of these functions if you invoke them without defining them.

I just reviewed someone's code and noticed he did not do this.   

Robert

No comments:

Post a Comment

Comments require my approval before they appear. Be patient. It will take a day or two for your comment to appear.