I have a simple class Name:
class Name
{ private:
char nameStr[30];
public:
Name(const char * = "");
char * getName() const;
void print() const;
};
I am having two problems, which are just a bit difficult for me wrap my head around. The constructor is supposed to take an argument of const char * and copy that into the nameStr array. However, this is what I have tried and is not working:
Name::Name(const char * setName)
{
&nameStr = setName;
}
It gives me the error “invalid lvalue in assignment”. If I remove the reference in front of nameStr, it still errors, saying “incompatible types in assignment of ‘const char*’ to ‘char[30]'”. Not quite sure what I’m missing.
The other problem is the accessor method:
char * Name::getName() const
{
return &nameStr[0];
}
I have the same problem, it errors “invalid conversion from ‘const char*’ to char*'” and I can’t for the life of me figure out how to make it return a pointer to a const char… I’ve been searching to avail. Found plenty of info on const, but can’t quite figure how to apply it to my situation. Any help would be greatly appreciated!
I would recommend you use an std::string, but first you need to know how pointers work.
Let’s take your first problem:
&nameStr = setName;Here,
nameStris an array of chars, for storing your name.&nameStrrefers to the address of this array. You cannot set the address of a variable of any sort, it is illegal. For example,&a = &b(where a and b are ints) is just as illegal. Next you tried,nameStr = setName;and it said incompatible conversion fromconst char* to char[30]. What you are trying to do is assign one pointer to another. This doesn’t actually copy the data. To copy the data, you need to do this manually, e.g.:Note, the comparion with
setName[n-1]instead ofsetName[n]is so the NULL character gets copied.For your next problem,
cannot convert const char* to char*. Taking the address of a variable will always yeald a constant pointer, because you are not allowed to change the address. Also note that&array[0]is essentially the same asarraybecause you a dereferencing, then re-referencing it, thus making the process unnecessary. You need to state your getName() function as returningconst char*and in it, returnnameStr.A word on arrays: Arrays are like other datatypes, except that they contain multiple of a datatype, not one. When referring to an array, its type is of a pointer to its member type. For example, an array of ints would be treated like an
int*. The pointer points to it’s first element. This means that using [] on an array will dereference the pointer to any of its elements.Good luck with C++!