0

If we have

class A {
private:
public:
  A(int a, int b) {std::cout << "You passed two numbers!;}
};

and I wish to create another constructor where the value of a is assumed 0 and we pass the value of b, will these two produce the same result:

// First variant
A(int b) : A(0, b) {}
// Second variant
A(int b) {A(0, b);}

I'm asking since in one of my codes I have

A(int minPrice, int maxPrice) {
  if (minPrice < 0 || maxPrice < 0)
    throw std::range_error("Illegal price");
  A::minPrice = minPrice;
  A::maxPrice = maxPrice;
}

and this produces an issue when I use the second variant; namely, when I call A(0, maxPrice) from inside that new one-parameter constructor.

nocomment
  • 119
  • 6
  • 2
    The second variant is just totally wrong. C++ is not Java. You don't call constructors like that, it doesn't do what you want. – n. m. could be an AI Jun 23 '22 at 12:10
  • 2
    @nocomment Use the first variant as it is the only valid option here. See the [dupe](https://stackoverflow.com/questions/13961037/delegate-constructor-c), it is explained there that delegation only works in constructor initializer list. – Jason Jun 23 '22 at 12:11
  • I have not seen a constructor written as the "Second variant" shown here before. Maybe it isn't a variant of a constructor. It just isn't correct. – Ryan Zhang Jun 23 '22 at 12:12
  • The second variant will make a local temporary A object, and then destruct that local object at the end of the statement. – Eljay Jun 23 '22 at 12:16

0 Answers0