views:

121

answers:

3
struct Base{
    Base(Base &){}        // suppress default constructor
};

struct Derived : Base{
};

int main(){
    Derived d;
}

The code shown gives error because the default constructor (implicit) of 'Base' is suppressed. Indeed the standard says in $12.1 "If there is no user-declared constructor for class X, a default constructor is implicitly declared."

There are three things:

a) Does the standard say anywhere that if the user declared constructor is present in a class, the default constructor (implicit) is suppressed. It is bascically the above phrased negatively or is it once again implied :)?

b) Why is it that way?

c) Why the same rules do not apply for the default destructor?

+7  A: 

I think that a) is sufficiently clearly implied by your quote.

As for “why” – quite simple: a default constructor is not always meaningful; if there were no way to suppress it, this would weaken C++ substantially.

As for c), a class without destructor (no “default”, just plain destructor) is simply not meaningful.

Konrad Rudolph
A: 

The shortest answer is because you declared a constructor for the class Base, no default constructor is created (thus the suppression). You cannot initialize Derived because Derived has no default constructor to call on class Base. (this is because the default constructor of derived that is generated for you can only construct it's parent class with the default constructor)

Stefan Valianu
+1  A: 

a) Does the standard say anywhere that if the user declared constructor is present in a class, the default constructor (implicit) is suppressed. It is bascically the above phrased negatively or is it once again implied :)?

Yes, that is the meaning

b) Why is it that way?

Most likely, if you have a user-defined constructor, it means special work needs to be done to initialize the object. It makes sense to disable the implicitly generated default constructor in such a case, because it likely won't do any of the special work.

c) Why the same rules do not apply for the default destructor?

Well, perhaps it would make sense for the language to enforce the "rule of three" (if you define one of copy constructor, assignment operator or destructor, chances are you need to implement all three), but it just doesn't.

Perhaps the rationale is that there are several ways to initialize a class, but assignment and destruction often works the same way (memberwise assignment, run destructor of all members).

UncleBens