Strange compiler behavior regarding default constructors in C ++

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

class TestClass2
{
private:
    TestClass testClass;
}

Why does this code compile fine even if we did not provide a default constructor?

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

Thank.

+3
source share
3 answers

When you specify a constructor without a default without specifying a default constructor, a default constructor does not exist.

, , TestClass2. TestClass2 , TestClass , .

.

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

, , - , .

+4

//etc. TestClass2.

, , TestClass2 -. , .

( . ++ , .)

+2

A compiler complaining that it never happens is a quick way to get developers to turn off all warnings.

0
source

Source: https://habr.com/ru/post/1728711/


All Articles