How to properly return reference to class member?
Hi, suppose this class:
Code:
class Foo {
protected:
QPoint& bar() const;
private:
};
QPoint& Foo::bar() const {
return m_bar;
}
I get this error:
error: invalid initialization of reference of type ‘QPoint&’ from expression of type ‘const QPoint’
However it works if I change it to this:
Code:
QPoint& Foo::bar() const {
return (QPoint&) m_bar;
}
1) I don't understand why the compiles says my QPoint is const.
2) Is it ok to leave the cast there?
Re: How to properly return reference to class member?
A method can't be const if it returns a non-const reference. Either make that method non-const or make the reference const. This is basic C++, you know... I'm moving the thread to a proper forum.
Re: How to properly return reference to class member?
1. You declared the member function bar() to be const; that implies that the class and all its data members (excepting any that are declared mutable) are treated as const within that function.
2. No. You should either return a const reference, return a value instead of a reference, or remove the const specifier from the function.
Which you choose depends on how you intend the return value to be used. If you don’t have a clear reason for using a reference (const or not), for a small data structure like QPoint you should probably be returning a value.
Re: How to properly return reference to class member?
Quote:
Originally Posted by
Coises
for a small data structure like
QPoint you should probably be returning a value.
Or a const reference.
Re: How to properly return reference to class member?