Accessor returning a private field char array?

Been stuck at this point for a while now and can't seem to find an answer..

This is the header file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#ifndef Student_hpp
#define Student_hpp

#include <string>
#include <stdio.h>

class Student {
  
private:
    char firstName [16];
    char lastName [16];
    
public:
    Student(std::string, std::string);
    
    char* getFirstName() const;
    void setFirstName(std::string);

    char* getLastName() const;
    void setLastName(std::string);
 
};
#endif


This is the accessor...
1
2
3
4
char* Student::getFirstName() const {
    return firstName;  //Error code here says...
}                      //Cannot initialize return object of type 'char *' with 
                       //an lvalue of type 'char const[16]' 

Return a pointer to const char.
 
const char* getFirstName() const;
Oh! I see now.

So the return type of a const function, if any, should always be const as well?
Yes, when returning a pointer or reference to something that is stored inside the object you normally want it to be const if the function is marked const, otherwise it provides a way of modifying the object even when you are not supposed to.

1
2
3
4
5
6
7
8
// This function promise not to modify the student object that is passed to it.
void foo(const Student& student)
{
	// But if getLastName() returned a pointer to a non-const char there would
	// be nothing preventing you from making changes to the student's name.
	char* str = student.getLastName();
	str[0] = 'A'; //The student's name now starts with an A.
}
Topic archived. No new replies allowed.