Since I'm a beginner in c++, some questions don't quite understand. This question came across by accident while I was reading C++ primer 5th.
I have a Cat
class with 3 different constructors(named by Constructor 1, Constructor 2, Constructor 3):
class Cat {
friend class Cats;
private:
std::string name;
public:
Cat() = default;
// Constructor 1
Cat(std::string n): name(n) {
std::printf("Call: Cat(std::string n)\n");
}
// Constructor 2
Cat(std::string& n): name(n) {
std::printf("Call: Cat(std::string& n)\n");
}
// Constructor 3
Cat(const std::string& n): name(n) {
std::printf("Call: Cat(const std::string &n)\n");
}
};
And I want to instantiate the class in two different ways:
class C7T17_Main {
public:
void run() {
// Instantiation 1
Cat cat(std::string("Cathy"));
// Instantiation 2
std::string s("Mike");
Cat cat2(s);
}
};
Then the problem comes:
For
Constructor 1
:Instantiation 1
andInstantiation 2
both work well
For
Constructor 2
:Instantiation 1
raises an error. The compiler complains that 'Candidate constructor not viable: expects an lvalue for 1st argument'Instantiation 2
works normally.
For
Constructor 3
:Instantiation 1
andInstantiation 2
both work well
My guess is:
Instantiation 1
does not actually create a variable, but a temporary value for initializing cat, so it is not suitable as a reference parameter.For
constructor 3
, the const reference parameter represents a constant that can accept a temporary value for initialization
Looking forward to your help. :)