Search code examples
c++constantsstrcmp

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.


Solution

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