Moshe Magnes
Moshe Magnes

Reputation: 393

Initializing base class with parameters generated by derived [C++]

I have a situation where I have some base class Base, from this class i derive DerivedA and DerivedB. Lets assume that the c'tor for Base looks like this:

Base(int a) : m_a(a) {}

now the problem is, that class DerivedA and DerivedB each use some algorithm to determine said "a", so doing DerivedA() : Base(a) is impossible, as a is being generated in the constructors body.

What solutions are there for such problem?

Upvotes: 1

Views: 74

Answers (2)

C. E. Gesser
C. E. Gesser

Reputation: 821

You can create a private static function to initialize a

class DerivedA : public Base{
public:
  DerivedA() : Base(compute_a())
  {
  }
private:
  static int compute_a() {
    //...
  }
};

If possible, you can also convert Base to a template and make use of the Curiously recurring template pattern.

template<typename Sub>
struct Base {
  int a;
  Base() : a(Sub::compute_a()) {}
};

struct DerivedA : Base <DerivedA> {
  static int compute_a() {
    //...
  }
}

Upvotes: 0

Davidbrcz
Davidbrcz

Reputation: 2397

Half constructing an object is always a bad idea. either you don't construct it either you fully construct it.

In you case the best solution is to use a free function

int complexCalculation(int a){...}
DerivedA():Base(complexCalculation(a))
{

}

Or you can choose to use a private (or protected) static function

struct DerivedA{
DerivedA():Base(complexCalculation(a))
{

}
private:
static int complexCalculation(int a){...}
};

Upvotes: 4

Related Questions