yungman
- 5,741
- 294
Thanks for the reply.jtbell said:I think the reason why it's not an error to omit the default constructors, is that in this program, the compiler never actually looks for a default constructor. The member declarations A1 a1; and B1 b1; by themselves do not invoke any constructors. That happens only when T1's constructor is invoked; that constructor explicitly invokes the non-default constructors A1 (int k) and B1 (int k), so the compiler never needs to look for a default constructor A1 () or B1 ().
Try removing either b1( tk ) or a1( tk ) from the initializer list for T1( int k ) and see what happens. This will force the compiler to look for a default constructor.
Here's a simpler program that illustrates the behavior that you're seeing:
C++:#include <iostream> using namespace std; struct A { int ka; A( int k ) { ka = k; cout << "A: " << ka << endl; } }; int main() { cout << "I'm not constructing any objects of type A." << endl; return 0; }
This compiles successfully for me. Now, in main(), first add A a; which looks for a default constructor (and edit the output to cout if you like). Then change it to A a(3); .
But it sure gave me a compiler error if I write it in my old way. I have to delete it to make it work.
C++:
#include <iostream>
using namespace std;
struct A1
{
int ka;
A1( int k)
{ ka = k; cout << "A1: " << ka << endl; }
};
struct B1
{
int kb;
B1( int k )
{ kb = k; cout << "B1: " << kb << endl; }
};
struct T1
{
int tk;
//I cannot put A1 a1; B1 b1; here unless I write a default constructor.
T1(int k)
{
tk = k;
B1 b1(tk);
A1 a1(tk);
}
};
int main()
{
T1 t1( 3 );
}
Please read line 18. This is a working program, but if I put A1 a1; B1 b1; in line 18, compiler will give me error unless I actually write in the default constructor.
If you look at the new syntax, compiler does not flag an error. That program does not have a default constructor, It is inconsistent. It's the new syntax that is different.
Thanks