0

I want my "no parameters" constructor to call another constructor, with some default constant value (as, if no value was delievered, use the default value);

I used an initialize list for the "no parameters" constructor, which calls the another constructor, with DEFAULT as a parameter. There, I I used an initialize list to initialize the constant value.

class Foo{
    public:
    Foo() : Foo(DEFAULT) {};
    Foo(int num) : DEFAULT(4) { /*do something with num */};
    const int DEFAULT;
};

My problem here is that DEFAULT is initialized only after I called the other constructor - so yes, DEFAULT will be 4, but num will have some garbage value.

I tried to change the order, but it doesn't seem to work, as I'm getting the same result.

class Foo{
        public:
        const int DEFAULT;
        Foo(int num) : DEFAULT(4) { /*do something with num */};
        Foo() : Foo(DEFAULT) {};
};

I would be glad to know how can I overcome this problem - how to use a constant value of a class inside the class constructor?

Matan
  • 39
  • 4
  • It's not entirely clear to me what you want here. Maybe just a single constructor with a single argument that has a default value? Like: `Foo(int num = 1234) : DEFAULT(num) {}` – Adrian Mole Dec 01 '22 at 11:49
  • 4
    Essentially, you're trying to initialize `DEFAULT` with `DEFAULT`. – Jason Dec 01 '22 at 11:49
  • Also, not sure what you mean by "num will have some garbage value". It will have the value it is given in the call to the constructor. – Adrian Mole Dec 01 '22 at 11:50
  • @AdrianMole I want to let the users choose if they want to use a value when creating an instance of Foo. If no value was given, I want to use some constant value. So I'm calling the other constructor with that `DEFAULT` value, but it's not initialized yet. So your way uses the other consturctor, which gets a value, but I want the no-value-constructor to have that value too. – Matan Dec 01 '22 at 11:56
  • @AdrianMole when the 'regular' constructor uses the initialize list to call the 'advanced' consturctor, it calls it with `DEFAULT` as parameter, but `DEFAULT` is not initizalied yet. `Foo f;` for example. `Foo f(100);` won't have any problem – Matan Dec 01 '22 at 11:58
  • @JasonLiam I didn't look at this from this POV, interesting input. – Matan Dec 01 '22 at 12:00
  • Then why not 'hard code' a default value for `DEFAULT`: `const int DEFAULT = 1234;` then your default constructor need do nothing and the one with an argument can use that in the initializer: `Foo(int num) : DEFAULT(num) {}`. You're still not making things very clear, here. – Adrian Mole Dec 01 '22 at 12:02

0 Answers0