Click to open the original link
#include <iostream> using namespace std; // Empty class class empty { }; // A default constructor, a custom constructor class Base { public: Base() { cout << " default Base construct " << endl; m_nValue = 100; }; Base(int nValue) { cout << " custom Base construct " << endl; m_nValue = nValue; }; private: int m_nValue; }; // A compound default constructor class custom { public: custom(int value = 100) { cout << " default && custom construct " << endl; m_nValue = value; } private: int m_nValue; }; void main() { empty* pEmpty1 = new empty; empty* pEmpty2 = new empty(); Base* pBase1 = new Base; Base* pBase2 = new Base(); Base* pBase3 = new Base(200); custom* pCustom1 = new custom; custom* pCustom2 = new custom(); delete pEmpty1; delete pEmpty2; delete pBase1; delete pBase2; delete pBase3; delete pCustom1; delete pCustom2; } // Result: /* default Base construct default Base construct custom Base construct default && custom construct default && custom construct */
I. difference between parenthesis and non parenthesis
(1) parenthesis
a. if the bracket is empty, i.e. there is no argument, it is understood to call the default constructor;
b. if the bracket is not empty, there is an argument, which can be understood as calling an overloaded constructor or a compound default constructor.
(2) without brackets
Call the default constructor or compound the default constructor.
The difference between the default constructor and the compound default constructor
(1) default constructor: the compiler will provide a constructor for each class by default, which is called the default constructor. The default constructor general parameter is null.
(2) composite default constructor: a constructor with default values for all the user-defined formal parameters is called composite default constructor.
(3) relationship between the two: in a class, once there is a user-defined constructor, the default constructor provided by the compiler no longer exists. The user-defined constructor is the overloaded version of the default constructor. When the default constructor no longer exists, the user must customize another composite default constructor for this class (select one of all the custom constructors and assign the default value to all the formal parameters). No matter how many custom constructors (that is, overloaded versions of constructors), only one composite default constructor is allowed.