• 4415阅读
  • 0回复

C++ basics: hide default constructor [复制链接]

上一主题 下一主题
离线steinlee
 

只看楼主 倒序阅读 楼主  发表于: 2010-02-24
If the default constructor is not needed, hide it in the private part in order to avoid misuse.
For example:

class A
{
public:
     A( const int input_id ) { id = input_id; }

     int getID() const { return id; }
private:
    double id;
}

if this class has to be always created with the defined constructor,
put the default one in the private part like

class A
{
public:
     A( const int input_id ) { id = input_id; }

     int getID() const { return id; }
private:
    double id;
    A();
}

Then other users will never get a chance to do the following:
A a; //there will be a compiling error for this

Note that the compiler will define a default constructor if it is not defined
by the user.

Remember that debugging is expensive.
[ 此帖被steinlee在2010-02-25 06:30重新编辑 ]
Looking for remote C/C++ and Qt 兼职
快速回复
限100 字节
 
上一个 下一个