1

I want to create a class that can be intialized by an integer and a class that can be initialized by this first class so that it can also be initialized with an integer.

class class1 {
    int n;
    class1(int i) {
      n = i;
    }
};

class class2 {
    class1 n = 0;
    class2(class1 i) {
      n = i;
    }
};

int main() {
    class2 n = 2; //Doesn't work
    class2 n = (class1) 2; //Does work
}
4
  • 2
    The compiler is only allowed to do one implicit conversion.
    – Ted Lyngmo
    Commented Aug 8, 2020 at 21:24
  • 1
    class2 n {2}; works Commented Aug 8, 2020 at 21:45
  • You neglected to mention what your question is. You might see only one possible question coming from this setup, but do you really want to risk me coming up with a different one? (Actually, I see two potential "obvious" questions: one is "how" and one is "why".)
    – JaMiT
    Commented Aug 8, 2020 at 23:35
  • @JaMiT I think the question may well have been "Why doesn't it work" or "How can I make it work" ;). That said, I came here to know about the C++ semantics, that is, whether multiple implicit constructors can be chained.
    – user4945014
    Commented Jun 6, 2021 at 22:58

1 Answer 1

5

You are not allowed to do more than one implicit conversion, so you have to provide an int constructor for class2.

You can do this easily by adding a delegating constructor that calls the constructor that takes a class1 argument:

class class2 {
  // ...
  class2(int i) : class2(class1{i}) {}
}

Here's a demo.

Also, assuming that the constructor taking a class1 doesn't do anything more complicated than initialize n, you could simply do:

class class2 {
  // ...
  class2(int i) : n{i} {}
}
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.