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;
}
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.
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
constchar* 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.