0

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.

3
  • Are you asking to write a shorter constructor? Commented Dec 18, 2019 at 12:47
  • 3
    @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. Commented Dec 18, 2019 at 12:50
  • 1
    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? Commented Dec 18, 2019 at 13:28

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.