2

I've this this kind of code used in some source, so I tried it and it works:

struct B {
    int x, y;

    B (int _x, int _y): x(_x), y(_y) {}
};

struct A {
    B b;

    A (B _b): b(_b) {}
};

int main()
{
    A a {{3, 4}};

    return 0;
}

Can anyone explain how is this "implicit instance" constructed and point me to where it is documented? If I got it correctly, A a {{3, 4}}; is a shortcut for A a2 {B{3, 4}};. Is this correct?

How can the compiler understand that I'm trying to get a new implicit instance of B if, for example, I overload the constructor so that it accepts another class that can be constructed with two ints?

Thanks

1
  • If you added another overload, that overload would take two arguments, so it can easily be distinguished from the present one, which takes one argument. Commented Apr 3, 2014 at 22:36

1 Answer 1

1

There is only one constructor in A which matches an initializer list with two arguments. If you would add a second constructor to A which for example take a class C similar to B, than it would be ambiguous and give a compiler error.

The complete rules to resolve overloads are a bit complicated. Have a look for example here.

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

6 Comments

Hmm.. "which match with your two arguments" I guess one could say that, even though it's simplifying a bit. {3, 4} is a single argument (initializer, but not an expression). It is checked against all three constructors, but two are forbidden via an obscure rule in [over.best.ics]/4 IIRC.
What are those "your two arguments"? I see only one argument?
I think my problem is that an exhaustive answer to this question is complicated, and probably beyond the scope of the OP; see e.g. stackoverflow.com/q/20714273/420683 IMO your simplification describes the intent of the rules now.
@dyp: Are you sure the automatic constructors survive the declaration of the user defined one?
@Deduplicator Yes, it's not a copy/move constructor that's user-declared. Otherwise, you wouldn't be able to copy/move objects of that type (w/o explicitly defining/defaulting the copy/move ctors and assignment-ops). There'll be no compiler-generated default ctor, though.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.