Overloading Operators with char c++ - c++

I am working on a homework for class on overloading operators. The problem I am having is with a char.
RetailItem &RetailItem::operator=(const RetailItem &objRetail) {
this->description = objRetail.getDescription();
this->unitsOnHand = objRetail.getUnitsOnHand();
this->price = objRetail.getPrice();
return *this;
}
I am getting a message on Visual Studio:
a value of type const char * cannot be assigned to an entity of type char *.
I have done some research and not found anything. If anyone can help, thanks in advance.
EDIT:
I will add the getDescription function to provide more information. Also the description is a *char.
const char *RetailItem::getDescription() const{
return description;
}

Probably RetailItem::description is char* and RetailItem::getDescription casts this char* to const char* and returns that. You can add const qualifiers implicitly, but you cannot remove them the same way in the assignment:
this->description = objRetail.getDescription();
And you probably shouldn't. This will make two RetailItems referring to the same resource without managing its lifetime properly, as well as not freeing the memory held previously (if it is indeed a pointer to a dynamically allocated array).
This boils down to: you should prefer using std::string over arrays.

Reason might be mismatch between data type of "member variables" which you used in the class and the return values of the function.
const char *RetailItem::getDescription() const{
return description;
}
Remove const before function , keep it char *RetailItem::getDescription() const only .It should work

Related

How to initialize non-const member variables with const actual parameter?

When I initialize the constructor with the given data type of the parameter, I find that it goes wrong with the explaination that " const char* values cannot be assigned to char* entities".
class TString
{
private:
char* m_pData;
int m_nLength;
public:
TString();
TString(const char* pStr);
······
}
TString::TString(const char* pStr) {
this->m_pData = pStr;
}
What should I do to solve this problem? If possible, give me a right example.
Thanks in advance and apolpgize for my ignorance.
Const char * generally are prefined static compiled strings that cannot be changed because they are locked in the source code, or they come from some immutable source. This is in part, why they are marked const to prevent people from trying to change them.
The easiest solution to this problem is to take the const char * and make a copy of it on the heap, then it is no longer constant.
For example:
#include <string.h> // for strdup
...
TString::TString(const char* pStr) {
m_pData = strdup(pStr); // this will malloc and copy the string accepting const char * as input.
}
One thing you will need to consider, the m_pData is now on the heap, so in the destructor, you will want to free this data otherwise you will have a memory leak.
TString::~TString(){
free(m_pData);
}
You will also want in the TString() constructor to set the m_pData=NULL too.
This will work with strings, but if it's binary data i.e. no terminator allocate the data using malloc and use a memcpy, like:
m_pData=(char *)malloc(m_nlength*sizeof(char));
memcpy(m_pData,pStr,m_nlength);
Or some such.

C++ const "and the object has type qualifiers that are not compatible with the member

I'm new to C++ programming and in my OPP class we were requested to create a phone book.
Now, in the lecture the Professor said something about that if you want to make sure that your variable that is being injected to a method doesn't get changed you must put const on it.
here is my code so far.
private:
static int phoneCount;
char* name;
char* family;
int phone;
Phone* nextPhone;
public:
int compare(const Phone&other) const;
const char* getFamily();
const char* getName();
and in Phone.cpp
int Phone::compare(const Phone & other) const
{
int result = 0;
result = strcmp(this->family, other.getFamily());
if (result == 0) {
result = strcmp(this->name, other.getName);
}
return 0;
}
I keep getting "the object has type qualifiers that are not compatible with the member"
when I try to call to strcmp inside my compare function.
I know that I can just remove the const in the function declaration and it will go away, but I still doesn't understand why it's showing in the first place.
Help would be greatly appreciated.
You need to add const qualifier for getters const char* getFamily() const;. This way these getters can be invoked on objects of type const Phone & that you pass into function.
Also other.getName should be other.getName().
Your signature
int Phone::compare(const Phone & other) const
means inside that function you need to ensure you don't change the Phone instance.
At the moment, your function calls const char* getFamily() (and getName, which you've missed the () call from). Neither of these functions are const, hence the error.
If you mark these as const too, it will be ok.
In addition to the other answers that correctly suggest const qualifying your getters, you can access the data members of other directly, avoiding those calls.
int Phone::compare(const Phone & other) const
{
int result = strcmp(family, other.family);
if (result == 0) {
result = strcmp(name, other.name);
}
return result;
}

Encapsulation and const issues

I have a problem in a c++ assignment that cannot be solved. Lets say this - the program works only if the membervariable (a pointer to an char-array) i public. But according to the rules it must be private and one should be able to access it through a public member-method.
Here is the definitions:
private:
char* _strPtr();
int _strLen;
public:
const char* getString();
const char* String::getString() {
return _strPtr;
}
And here in an overloaded member-function the problem arises
const String operator+(const String string, const char *ch) {
String temp;
strcpy(temp.getString, string.getString());
strcat(string.getString(), ch);
return temp;
}
I get error-messages such as
invalid arguments Candidates are ; unsigned int strlen(const char *)
invalid arguments Candidates are ; const char* getString()
I cannot see how this could be solved. I have really tried with everything. Would be glad if someone could come with good tips.
As - I said in th beginning - the program works, but after encapsulating the membervariable and putting a const ahead of the function - it doesn't work any more.
You are defining char* _strPtr();, which is the definition of a function returning a char*. Probably what you meant was to define char* _strPtr;

Subscripting a reference to const

I'm here looking at some C++ code and am not understanding something. It is irrelevant but it comes from a YARP (robot middleware) tutorial which goes with the documentation.
virtual void getHeader(const Bytes& header)
{
const char *target = "HUMANITY";
for (int i=0; i<8 && i<header.length(); i++)
{
header.get()[i] = target[i];
}
}
Now, header is a reference to const and thus cannot be modified within this function. get is called on it, its prototype is char *get() const;. How can header.get() be subscripted and modified ? The program compiles fine. I may have not understood what happens here but I'm basing myself on what I've read in C++ Primer...
I would very much appreciate a little clarification!
Have a nice day,
char *get() const;
The right hand const means "this member doesn't alter anything in the class that's not mutable", and it's honoring that - it isn't changing anything. The implementation is probably something like this:
char *Bytes::get() const
{
return const_cast<char *>(m_bytes);
}
The pointer that is being returned, however, is a simple "char*". Think of it this way:
(header.get())[i] = target[i];
// or
char* p = header.get();
p[i] = target[i];
Whoever designed the interface decided that the content of a const Byte object can be modified by stuffing values into it. Presumably they've done whatever hacks they needed to make header.get()[i] modifiable. I wouldn't use this code as an exemplar of good interface design.
Looking at the doc:
struct Bytes {
char* get() const; // works
char*& get() const; // would not work
char* mem_;
};
This code is perfectly valid, even though it is bad practice. The
problem is that a copy of the pointer is made and the constness of the
class is lost. constness in C++ is largely conceptual and easy to
break (often even without consequences). I'd complain to the
implementer. It should look like this:
struct Bytes {
char* get(); // works
const char* get() const; // would not work
char* mem_;
};
header.get() should returns char*, assuming it as base address and indexed with [i] and string in target coped to that location.
#antitrust given good point, return address can't be modified by address content can e.g.
char x[100];
char* get() const
{
return x;
}
int calling function you can do like:
get()[i] = target[i];
it will copy target string to x, this method can be useful when x is private member to class, and you are to copy in x.
Edit if get() is a inline function then calling get() function in a loop will not effect performance., I mean such function should be defined inline.

Create String object from std::string by overloading = operator

I've tried several options but my compiler does not pick up the operator overloading or something else is wrong. I'm using XCode 4.5.2 with default Apple LLVM compiler 4.1.
The error I get is this: Assigning to 'cocos2d::CCString *' from incompatible type 'const char [5]'
on these lines:
CCString *s_piece__locks = "TEST";
cocos2d::CCString *s_piece__locks2 = "TEST";
My .h code:
CCString& operator= (const std::string& str);
// CCString& operator= (const char* str); // this doesn't work either
const CCString& operator = (const char *);
My .cpp code (even though this is irelevant):
CCString& CCString::operator= (const std::string& str)
{
m_sString = CCString::create(str)->m_sString;
return *this;
}
const CCString& CCString :: operator = (const char* str)
{
m_sString = CCString::create(str)->m_sString;
return *this;
}
Your help is very appreciated, thanks!
The error message Assigning to 'cocos2d::CCString *' from incompatible type 'const char [5]' suggests that you are assigning a char array to a pointer to cocos2d::CCString.
This should work:
char bar[] = "ABCD";
cocos2d::CCString foo;
foo = bar;
CCString *s_piece__locks = "TEST";
cocos2d::CCString *s_piece__locks2 = "TEST";
What the heck is this supposed to do? Declaring a pointer does not generate any object except the pointer itself. So basically, for this to "work", there would need to be another CCString object around already, that happens to represent the string "TEST". But even if that's given, how is C++ supposed to know which one to point to? It would need to look "TEST" up in some kind of e.g. hash map.
None of this makes any sense. Change your code to either
Direct use of object on stack:
cocos2d::CCString s_piece;
s_piece = "TEST";
Assigning new content to an object that resides somewhere else. You'd normally use a reference for this, e.g.
void assign_test_to(cocos2d::CCString& target) {
target = "TEST";
}
it's also possible with a pointer
void assign_test_to_ptr(cocos2d::CCString* target) {
*target = "TEST";
}
but don't do that unless you have a specific reason to.
In principle, there's another possibility:
cocos2d::CCString* s_piece_locks = new CCString;
*s_piece_locks = "TEST";
but you want to avoid this, as it can very easily lead to memory leaks. What would be ok is
std::unique_ptr<cocos2d::CCString> s_piece_locks = new CCString;
*s_piece_locks = "TEST";