Writing non-default constructor supersedes compiler generated default constructor?

If I have a basic data struct with an initialization constructor, the compiler seems to no longer generate a default constructor:

struct MyStruct
   int mVarA;
   int mVarB;

   MyStruct( const int a, const int b ): mVarA(a), mVarB(b) {}

MyStruct mystruct;

Compiler error: expects constructor with 2 arguments.

So instead I will have to add default arguments to this constructor:

MyStruct( const int a=1, const int b=2 )

Since it is a simple data type I suppose I could not write any explicit constructor and initialize objects manually

MyStruct mystruct;
mystruct.a = 1;
mystruct.b = 2;

My main motivation for having the explicitly defined constructor is so that the compiler will warn me if initialization parameters changes somehow, though with default arguments sometimes this may not work.

Ideally I'd like to avoid writing explicit constructor functions when it's unnecessary.

I should note I only have worked with C++98 for the most part I am unfamiliar with C++11, if that makes any difference here.
Last edited on
If you will remove the constructor then your structure will be an aggregate and you might initialize it the following way

MyStruct mystruct = { 1, 2 };

At the same time you may create objects without initialization

MyStruct mystruct;

If your compiler supports the C++ 2011 Standard then you could write

MyStruct mystruct = {};

I am sorry but even with old compilers this record is valid.:)

The new syntax is without the equal operator.

MyStruct mystruct {};
Last edited on
Yes, defining any constructor will remove the default constructor.

If you want to force the default constructor to be generated, I believe the syntax is:
MyStruct() = default;

C++11 only however.
It doesn't take anything to write a default ctor normally:

MyStruct() { }

Thanks vlad

"The new syntax is without the equal operator.

MyStruct mystruct {};"

I got the compiler warning about -std=c++0x being required so I added the option. Wow. Compile time increased by over 4x (:42 seconds to recompile entire project vs 3:48 with c++0x). I will use the = syntax to avoid the warning.
Which compiler (version)?
gcc (g++) 4.6.1
Topic archived. No new replies allowed.