2

I have a class with two constructors.

class Foo {
  Foo(B b) {... }

  Foo(int n) : Foo(buildBFromInt(n)) {} ??
}

The first takes some object and I would like to have a second one that first creates the object from a simpler type. Is this possible ?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
ElefEnt
  • 2,027
  • 1
  • 16
  • 20
  • 2
    Unless you need special processing, you could add a non-explicit constructor in the `B` class that takes an `int` argument, and avoid the [delegating constructor](https://www.ibm.com/developerworks/community/blogs/5894415f-be62-4bc0-81c5-3956e82276f3/entry/introduction_to_the_c_11_feature_delegating_constructors?lang=en). Then your code would be compatible with the older C++ standards as well. – Some programmer dude Aug 04 '15 at 01:31
  • And if you need to do special processing (but please avoid code that could throw exceptions or that does input/output) then you can make the `B` constructor `explicit` and do e.g. `Foo(int n) : Foo(B(n)) {}`. – Some programmer dude Aug 04 '15 at 01:33

1 Answers1

8

It is possible since C++11. it is the delegating constructor, and you use the correct syntax.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 1
    The simple example happens to work, but delegating constructors don't solve the problem very well if the "inner" constructor has more than one parameter. – Potatoswatter Aug 04 '15 at 03:39