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...
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.