I’ve got the following class:
class BaseStyle {
private:
Style *style;
public:
BaseStyle(Style& theStyle);
const Style& getStyle() const;
void setStyle(const Style& theStyle);
};
I’m trying to store the reference passed in the constructor in style, and change that property when setStyle() is called. I expected to be able to have a property Style& style, however, then I read c++ reference properties can not be changed after initialization. Now I think it’s best to store the reference in a pointer, but how do I do that? I can’t just do style = theStyle, right?
You should implement your class like this:
Explanation: References are implemented as pointers. This is not clearly stated in the docs by there is no compiler that is doing anything different from this. The difference is only syntactical. This means, that by writing
&theStyleyou take an address of the object that can be assigned to the pointer.There is nothing bad in taking address of the object, referenced by the reference and assigning it to a pointer.