I see several problems with your code.
First, is that the reference variable has to be initialized and not assigned. So I would expect a compiler error in line 23. This should be written as:
1 2 3 4
|
User::User():
_ref(ImplBase())
{
}
|
Which brings me to the second problem.
In order to use the reference to base class you need to have the actual object somewhere in memory - be it on stack or dynamically allocated. What happens in line 23 of your code is that a temporary variable is created on stack and then _ref points to it. However, this temporary variable is destroyed when constructor exits.
I am a bit confused about why do you even want to use the Base& in this case when you know exactly which implementation you will use. In this case you can just use a member variable
ImplBase _impl;
instead of
Base& _ref;
.
If you really want to have a base-class reference, then you have two options. First, is
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class User
{
public:
User();
private:
Base &_ref;
};
User::User()
: _ref(*(new ImplBase()));
{
}
|
which will create an instance of ImplBase in dynamic memory. However, don't forget to destroy the object in destructor (
delete &_ref;
). Also to ensure correct destruction of the derived object through a pointer to the base object you need to make the destructor virtual.
The second option is to have the instance of ImplBase in your class:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class User
{
public:
User();
private:
Base &_ref;
ImplBase _impl;
};
User::User() :
_ref(_impl)
{
}
|
However, again, before using the base-class reference you need to decide whether and why do you need a reference in this case.