views:

74

answers:

3
class TestClass
{
public:
    TestClass(int i) { i = i; };
private:
    int i;
}

class TestClass2
{
private:
    TestClass testClass;
}

Why does the above code compile fine even when we have not provided a default constructor?

Only if someone instantiates TestClass2 elsewhere in the code, do we get a compile error. What is the compiler doing here? Seems strange...

Thanks.

A: 

A compiler complaining about things that never happen is a quick way to get developers to turn off all warnings.

Ignacio Vazquez-Abrams
+3  A: 

When you specify a non default constructor without specifying a default constructor, the default constructor doesn't exist.

You aren't attempting to call the default constructor until you try to call it explicitly as you are in TestClass2. If you instead in TestClass2 specified a constructor that initialized TestClass appropriately, you would have no error.

i.e.

class TestClass2
{
   TestClass m_testClass;
public:
   TestClass2():m_testClass(2){}
};

also use initializer lists wherever possible for performance, and if you call the parameter name and the member variable name the same it can be confusing for others.

Rick
+1  A: 

Because you don't need the default constructor to determine the size/type info/etc. of TestClass2.

The first time the default constructor is needed is when TestClass2 is initiated somewhere. This is when the compiler finds out the default constructor does not exist and complain.

(These are my speculations only. Check the C++ standards for what's actually happening.)

KennyTM