Const Reference vs. Reference, Member Function Overloading.

If I have the following class:

1
2
3
4
5
6
7
8
class Dog {
    int age;
    string name;
public:
    Dog() { age = 3; name = "Dumb dog";};
    void setAge(const int& a) {age = a;};
    void setAge(int& a) {age = a;};
};


And I initialise a Dog via:
 
Dog d


How do I get d to call the first setAge function with const int&? It keeps calling the second. I've tried several things, including:

1
2
3
4
5
6
7
8
9
10
11
12
13
d.setAge(10);

const int p = 10;
d.setAge(p)

const int x = 5;
const int& j = x;
d.setAge(j)

const Dog p;
p.setAge(10);



And none have used the first setAge. What am I missing? I have a feeling it has to do with rvalues and lvalues.
Last edited on
Are you sure? For me, calling setAge(10) calls the const one, and doing
1
2
int i = 1;
dog.setAge(i);

calls the non-const one. Try putting print statements in the functions (or debugging).

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
// Example program
#include <iostream>
#include <string>

class Dog {
    int age;
    std::string name;
public:
    Dog() { age = 3; name = "Dumb dog";};
    void setAge(const int& a)
    {
        std::cout << "setAge(const int& a)" << '\n';
        age = a;
    }
    void setAge(int& a)
    {
        std::cout << "setAge(int& a)" << '\n';
        age = a;
    }
};

int main()
{
    Dog dog;
    dog.setAge(10); // const int&
    
    int i = 4;
    dog.setAge(i); // int&
}


That being said, this is bad practice imo, and you should just have the const int& function.
Or, since it's just an int, just have void setAge(int age);

https://www.geeksforgeeks.org/function-overloading-and-const-functions/
Last edited on
Weird, you're right. const int& is triggered by r value. Maybe I just didn't see it, my bad.
Topic archived. No new replies allowed.