class myClass {
private:
int a;
public:
myClass(int a) : a{a} {}
int geta() const {
//a = 30; Won't work. Can't change a member variable of the class inside a member function
return a;
}
};
and we call from main():
1 2 3
const myClass obj{10};
cout << obj.geta();
//This is ok as myClass::geta() is defined as const.
Are my comments correct? And secondly, I know it is possible to use the const keyword before the return type as well. What does this do ?
> I know it is possible to use the const keyword before the return type as well. What does this do ?
For a non-class type like int(returned by value), the const qualifier is ignored.
1 2 3 4 5 6
// GNU: warning: type qualifiers ignored on function return type
// LLVM: warning: 'const' type qualifier on return type has no effect
constint foo()
{
return 900 ;
}
For class types and references there is a difference:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
struct Bar {
int member;
void something();
constint& ref() { return member; }
};
const Bar foo();
int main() {
foo().something(); // error, const Bar
Bar gaz;
gaz.ref() = 42; // error, const reference
}
The foo() returns an object. We can call member functions of a class object. (Non-class objects have no members). Whether the returned object is const or not, does affect what members we can call on it.