Reputation: 195
I have a class ModelRecorder
with contains a reference modelRef_
to another class OpModel.
class ModelRecorder : public CompositionalModel //This is an abstract base class
{
OpModel& modelRef_;
};
When an instance of ModelRecorder
is created and modelRef_
is initalized. Thats fine I unerstand that.
How would I write a copy constructor for ModelRecorder
so that if another instance is created, the reference memeber modelRef_
will be initalized with the previous created OpModel object?
Note that CompositionalModel
is an abstract base class.
In another class there is fucntion that returns a reference to CompositionalModel
he base class. I understand returning the narrower base class is a good OOP.
For example CompositionalModel& recordedModel();
I want to pass this reference to the base class to the copy constructor.
I tried this but it gives the error, which is correct modelRef
is in the dereived class ModelRecorder
.
error: ‘const class mv::CompositionalModel’ has no member named ‘modelRef_
mv::ModelRecorder::ModelRecorder(const CompositionalModel& arg) : CompositionalModel{static_cast<const ModelRecorder&>(arg)}, modelRef_{arg.modelRef_}
{
}
Upvotes: 10
Views: 9019
Reputation: 13424
There are 2 ways:
The first way - make compiler do it for you:
ModelRecorder(const ModelRecorder&) = default;
The second way - implement it yourself:
ModelRecorder(const ModelRecorder& arg)
:CompositionalModel{arg}, modelRef_{arg.modelRef_} {}
Note that you have to use the member initializer list, since we're dealing with references. The difference between the above code and this:
ModelRecorder(const ModelRecorder& arg)
:CompositionalModel{arg} {
modelRef_ = arg.modelRef_;
}
is that the later does not initialize the reference. It violates the rules, since references must be initialized, not assigned later. My best advice is to stick with the easy way, since it's the least possible to mess up using it
Upvotes: 10