menu

hjk41的日志

Avatar

More Effective C++ 4: Avoid gratuitous default constructors

Sometimes we can't initialize an object without any information. For example, an Emploree class may require an emploree ID, an no instance of Emploree should be created without ID. In such cases, we should avoid default constructors.
However, a class lacking default constructors may bring some trouble.
1. You may have trouble creating an array.


class Employee{
    public:
        Employee(const int ID);
};

Employee emArray[10];   // error! no default constructor for Employee


This problem can be addressed by using arrays of pointers.


Employee * emArray[10];
for(int i=0;i<10;i++)
    emArray[i]=new Employee[i];

2. Classes of no default constructors may not get on well with template-based constainer classes, for some of the implementations of container classes creates arrays of the template parameter type.

3. Base classes of no defulat constructors may be a pain to work with. When objects of derived classes are being initialized, default constructors of the base classes are called if you don't specify them in the constructors of the derived ones.


class B{
public:
    B(){cout<<"default constructor of B"<<endl;}
...};

class D:public B{
public:
    D(){cout<<"default constructor of D"<<endl;}
};

D d;


The output would be

default constructor of B
default constructor of D


If B don't have a default constructor, you will have to write something like this:


class B{
public:
    B(int i){cout<<"constructor with parameter of B"<<endl;}
...};

class D:public B{
public:
    D():B([i]parameter[/i]){cout<<"default constructor of D"<<endl;}
};

D d;


or your compiler will complain.

评论已关闭