ldg
ldg

Reputation: 15

const compile error on class method

I am receiving this error invalid conversion from ‘const char*’ to ‘char*’ from this code:

// in account.h
struct account {
    char* get_name ( ) const;
    char name[MAX_NAME_SIZE+1];
};
//in account.cxx
char* account::get_name ( ) const
{
    return name;
}

Can someone please help me?

Upvotes: 0

Views: 119

Answers (3)

Enrique Tobis
Enrique Tobis

Reputation: 1

Since get_name is a const method, all the members of the implicit object are const in the context of that method. By returning name as a char *, you are dropping the const qualifier from name. You could return const char *.

Upvotes: 0

Carl
Carl

Reputation: 44488

You're returning a non const pointer. You want to return a const char:

// in account.h
const char* get_name ( ) const;

//in account.cxx
const char* account::get_name ( ) const
{
    return name;
}

The reason is that your method is declared const, but the pointer you're returning could be used to modify name, which would be a violation of the method's const promise.

Upvotes: 0

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361732

The return type should be const char* as well:

const char* get_name ( ) const;

It is because in a const member function, this pointer becomes a const, as a result of which every member of the class becomes const, which means name which is declared as char[N], becomes const char[N] in a const member function. const char[N] can converts into only const char*, hence you need to make the return type const char*.

Upvotes: 2

Related Questions