const member functions

Hello,

Let's say we have a class defined like this:

1
2
3
4
5
6
7
8
9
10
11
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 ?
Last edited on
Sometimes the mutable specifier could get in the way:
https://en.cppreference.com/w/cpp/language/cv

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>


class MyClass {
public:
    MyClass(int my_a_arg, int my_b_arg);
    int getMyA() const;
    int getIncreasedMyB(int val) const;

private:
    int my_a;
    mutable int my_b;   // irrational usage of the mutable specifier
};


MyClass::MyClass(int my_a_arg, int my_b_arg)
    : my_a { my_a_arg }
    , my_b { my_b_arg }
{
}


int MyClass::getMyA() const 
{
    // my_a = 30; won't work: can't change a non-mutable member
    // variable inside a const member function   .
    return my_a;
}


int MyClass::getIncreasedMyB(int val) const 
{
    my_b += val;
    return my_b;
}


int main()
{
    MyClass mc( 13, 666 );
    std::cout << "mc.my_a: " << mc.getMyA()
              << "\nmc.my_b (decreased by 44): " << mc.getIncreasedMyB(-44)
              << '\n';
}


Output:
mc.my_a: 13
mc.my_b (decreased by 44): 622


> Are my comments correct?

Yes.


> 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
const int foo()
{
    return 900 ;
}

http://coliru.stacked-crooked.com/a/7ad6a9bf6fe665a3

Didn't really catch what the const before the return type did?
Last edited on
For a non-class type, it does nothing;
there is no difference between int foo(); and const int foo();
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();
  const int& 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.
Topic archived. No new replies allowed.