Reimundo Heluani Reimundo Heluani - 1 month ago 6
C++ Question

Two child classes that only differ in a static const member

I have a class

A
and two children
B
and
C
as follows:

class A {
private:
int x;
template<class T>
void setX(T &y);

public:
A();
};
class B : public A {
private:
static const double y;

public:
B();
};
class C : public A {
private:
static const int y;

public:
C();
};


Both children only differ in the type of their static member
y
. The implementation of both C and B is the same except on the initialization of the static member:

B::B() : y (1.2) { setX(y) }
C::C() : y (2) { setX(y) }


But the problem with this approach is that in the implementation file I have to write twice the same code for
B
and
C
. Is there a proper way to write this such that I do not need to write twice the call to
setX
?

In the real problem the classes are a little more complicated, but the situation at hand is the same. In particular, initialization of
y
requires non-trivial constructors and so it has to be in the implementation file.

Answer

You can write a constructor for A as a function template.

class A {
    //....
public: 
    template<typename T>
    explicit A(T& y) {
        setX(y);
    }
};

And call that constructor from child classes:

class B : public A{
    //...
public:
    B() : A(1.2), y(1.2)
    {}
};

Only problem is that base class constructor gets called first, so you need to repeat constant data value twice. You can easily macro it though.

Comments