0
votes

The following piece of core works fine:

class A {
public:
    int a;
    int b;
};

A obj{ 1, 2 };

If, however, one adds default constructor explicitly: A(){}, one has to add another one for brace-enclosed initializer list, like:

A(int a, int b):a(a), b(b) {}.

Is there a shorter form like, e.g.:

A(const A& ab) { *this = ab } ???

The one above doesn't work.

2
Are you asking to write a shorter constructor? - Frontear
@Frontear it seems like the question is, if it's possible to make A obj{ 1, 2 }; work without writing out the full A(int a, int b) constructor when a default constructor is explicitly present. - CompuChip
Why do you need default constructor? Perhaps you could use in-class member initialization instead (like this: class A { public: int a = 1; int b = 2; };) and have all benefits of compiler-generated constructors? - Yksisarvinen

2 Answers

1
votes
A(int a, int b):a(a), b(b) {}.

Is there a shorter form

No. Other than a few white spaces, this constructor is as short as it can be.

1
votes

Unfortunately not.

When you created a default constructor, you prevented yourself from initialising the class using aggregate-initialisation.

To be able to get back the ability to use that declaration syntax, you have to create another constructor that takes all the necessary arguments… and there is no shorter way to do that than what you have written.