returning char array in classes

i have created a class, and i want to create a getter function that returns char array. i made it const function because the func doesnt change any values, however, i get errors that the returning type is not the same. can you tell me how to fix that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 #define SIZE 2
//H CLASS DATA MEMBERS
class Product
{
private:
	int m_serial;
	char m_location[SIZE];
	int m_quantity;
	int m_productType;	//1-agricultural 2-milk 3-package.
	int m_area;

//H METHOD DECLARATION
char* getLocation()	const;

//CPP METHOD IMPLEMENTATION
char* Product::getLocation()	const
{
	return m_location;
}


THANKS!
i made it const function because the func doesnt change any values
You also must make sure that you do not allow caller to change object, for example by returning mutable pointers/references to innards.

Correct return type:

const char* getLocation() const;
thnx, but still not working, it says differnet type .....
maybe because i defined regular array? (i need array in size 2 )
my mistake, works!

can you please explain me again why const is needed in the beginning too?
and generally, when do i use const in the end/ beginning of the signature, or in the brackets.

thank you
why const is needed in the beginning too
Because otherwise you could change constant object data:

1
2
3
4
5
6
const Product product;
char* loc = product.getLocation();
loc[0] = 10; //Changes product, which is const, UB

const char* loc = product.getLocation();
loc[0] = 10; //loc points to constant, so we cannot do that. 
generally speaking try to avoid returning non-const pointer for getters . And avoid returning all the array , simply return a char it is more efficient and prone encapsulation since you dont want to display all your content.
Topic archived. No new replies allowed.