Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-const reference class member

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?

like image 670
Frog Avatar asked Aug 30 '26 01:08

Frog


1 Answers

You should implement your class like this:

class BaseStyle
{
    private:
        Style *style;
    public:
        BaseStyle(Style &theStyle) { style = &theStyle; }
        const Style &getStyle() const { return(*style); }
        void setStyle(Style &theStyle) { style = &theStyle; }
};

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 &theStyle you 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.

like image 178
Kirill Kobelev Avatar answered Sep 01 '26 19:09

Kirill Kobelev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!