开发者

Strange Compiler Behavior Regarding Default Constructors in C++

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

class TestCla开发者_开发知识库ss2
{
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.


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜