const method difficulty

This method works when it's not const but when i make it const i get an error:
invalid conversion from const char* to char*

btw this is in debian using g++, anyone know what's wrong with this?

Account.h prototype
 
char* getName() const;


Account.cpp
1
2
3
4
char* Account::getName() const 
{
	return name;
}
Make getName() return a const char*.
Last edited on
So do need the const at the beginning and end or just the beginning
Pointers are nasty. How about you use std::string instead?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string>

class Account
{
private:
    // ...
    std::string name;

public:
    // ...
    std::string getName() const
    {
        return name;
    }
};
the assignment told me to return a c-string so didn't have that option, but it works when returning a const char like Peter said. Im a little confused as of why though
Last edited on
1) A pointer is not an array. It is a number (representing a memory address, which is why we say it points to somewhere).

2) So when you write const char *p you mean "pointer p will not modify the data where it points".

3) By putting const behind a member function, it means that it doesn't modify the data of the class.

So that's why you use a const pointer, which guarantees... sigh... that it won't allow the data it points to, to be modified.
Topic archived. No new replies allowed.