I have a base class that updates an extern reference, and I want to build an inherited class that would embed this reference as a member. A kind of default initialization of the reference.
I came up with the following solution:
#include<iostream>
class Statefull
{
public:
Statefull( int& ref ) : _base_ref(ref) {}
int& _base_ref;
// update the extern variable
void work() { std::cout << ++_base_ref << std::endl; }
};
class Stateless : public Statefull
{
public:
// use a temporary allocation
Stateless( int* p = new int() ) :
// we cannot initialize local members before base class:
// _dummy(), Statefull(_dummy)
// thus, initialize the base class on a ref to the temporary variable
Statefull(*p),
_tmp(p),
_dummy()
{
// redirect the ref toward the local member
this->_base_ref = _dummy;
}
int* _tmp;
int _dummy;
// do not forget to delete the temporary
~Stateless() { delete _tmp; }
};
int main()
{
int i = 0;
Statefull full(i);
full.work();
Stateless less;
less.work();
}
But the need of a temporary allocation in a default argument of the constructor seems quite ugly. Is there a more elegant way to achieve this kind of default initialization while keeping a reference in the base class constructor?
I think this might work:
You can’t do without temporaries, but they don’t have to be in the classes definitions.