Reputation: 11
I'm following along with a C++ book titled "Starting Out with C++: From Control Structures Through Objects" by Tony Gaddis.
There's a programming example that I get an error on. The program creates a constructor for a class which takes two arguments. The two arguments are pointers to chars. Here's part of the class:
class ContactInfo
{
private:
char *name;
char *phone;
public:
ContactInfo(char *n, char *p)
{
name = new char[strlen(n) + 1];
phone = new char[strlen(p) + 1];
strcpy(name, n);
strcpy(phone, p);
}
}
When an object of the ContactInfo class is created, the program passes these values to the constructor.
ContactInfo entry("Kristen Lee", "555-2021");
This all seems to make sense to me, but I get an error when passing "Kristen Lee" to the constructor. The error says:
"no instance of constructor "ContactInfo::ContactInfo" matches the argument list. Argument types are: (const char[12], const char[9])"
I don't understand why this error shows up. The only thing I can think of is that we're trying to pass a value into a variable which holds memory addresses. But, I don't know enough about programming to know if this is the case. I doubt this would be in the textbook if it didn't work at all. Maybe it's a visual studio problem (the IDE I'm using)? I'd really appreciate any help I can get with this problem.
Upvotes: 1
Views: 914
Reputation: 206737
A string literal can decay to a char const*
, not a char*
. Hence, you should change your constructor to use char const*
.
ContactInfo(char const* n, char const* p) { ... }
As a general principle, unless you want a function to modify its argument, make it const
. That's always a better choice. It allows the function to be used using a const
object and a non-const
object. This applies to passing pointers as well as references to objects.
Upvotes: 0
Reputation: 7111
A string literal (e.g. "Kristen Lee"
) is a const char*
: it is unmodifiable by your program. Since the constructor of ContactInfo
takes only a char*
, the string literal does not match.
This is laid out in the compiler message:
no instance of constructor "ContactInfo::ContactInfo" matches the argument list. Argument types are: (const char[12], const char[9])
Here the compiler is telling you there's no match for the function ContactInfo::ContactInfo
and that the arguments you're passing as const char[12]
and const char[9]
.
Your problem can be very easily solved by using std::string
instead:
#include <string>
class ContactInfo
{
private:
std::string name;
std::string phone;
public:
ContactInfo(std::string n, std::string p) : name{n}, phone{p}
{}
};
Notice how much simpler that makes your code, as you no longer need 4 lines of code and to manage your own memory.
Upvotes: 1