tmlen - 8 months ago 71

C++ Question

`class Base {`

public:

Base(int a, int b);

};

class Derived : public Base {

private:

static std::pair<int, int> determine_a_and_b_(int k);

public:

explicit Derived(int k);

};

Derived::Derived(int k) :

// a, b from determine_a_and_b_(k)...

Base(a, b) { }

Is there any way to call

`determine_a_and_b_`

`Derived`

`a`

`b`

`Base::Base`

It seems that the only way would be to refactor

`Base`

`a`

`b`

`Derived::Derived(int k) : Base() {`

Base::init_(a, b);

}

Is there any better way to do this, without needing to change

`Base`

`determine_a_and_b_`

Answer

What you can do here is write a function that returns a `Base`

and in the function create the base from the `std::pair`

returned by `determine_a_and_b_`

. This allows you to conditionally initialize base in the member initialization list. You would have something like

```
class Base {
public:
Base(int a, int b);
};
class Derived : public Base {
private:
std::pair<int, int> determine_a_and_b_(int k);
Base create_base(std::pair<int, int> params) { return Base(params.first, params.second); }
public:
explicit Derived(int k);
};
Derived::Derived(int k) : Base(create_base(determine_a_and_b_(k)) {}
```

Source (Stackoverflow)