class Dog {
int age;
string name;
public:
Dog() { age = 3; name = "Dumb dog";};
void setAge(constint& 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);
constint p = 10;
d.setAge(p)
constint x = 5;
constint& 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.
// Example program
#include <iostream>
#include <string>
class Dog {
int age;
std::string name;
public:
Dog() { age = 3; name = "Dumb dog";};
void setAge(constint& 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);