Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constness for reference class members

Tags:

c++

constants

I have a couple of classes one of which keeps reference to the object of other:

class Inner {};

class Outer {
    Inner & in;

public:
    Outer(Inner & in) : in(in) {}
};

What if I have to create Outer object from const reference to Inner? Am I have to write specific class, say OuterConst, for this?

UPD: Any neat solutions using templates? In order to avoid duplication of code in OuterConst class.

UPD2: when Inner comes without const it should be modifiable (so I can't just add const to Inner member in current implementation of Outer).

like image 596
Artem Pelenitsyn Avatar asked May 19 '26 11:05

Artem Pelenitsyn


1 Answers

What if I have to create Outer object from const reference to Inner?

Well, you can't. That's pretty much it. If Outer only needs to call const member functions of Inner, then make it a const reference- else, your class depends on a mutable Inner object and you should not create an Outer object from a const reference.

like image 132
Puppy Avatar answered May 20 '26 23:05

Puppy



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!