Yoni hodefi
Yoni hodefi

Reputation: 113

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.

Upvotes: 1

Views: 6487

Answers (3)

Caleth
Caleth

Reputation: 62676

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;
}

Upvotes: 2

doctorlove
doctorlove

Reputation: 19232

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.

Upvotes: 2

user7860670
user7860670

Reputation: 37513

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().

Upvotes: 9

Related Questions