Reputation: 355
I am brand new to C++ and am struggling with the idea of using arrays and returning pointers.
I have a class Student
in a .h
file:
class Student {
public:
// stuff
int* GetNumDaysPerCourse() const;
// stuff
private:
//stuff
int numDaysPerCourse[3];
// stuff
};
And I am trying to implement it in a .cpp
file:
int* Student::GetNumDaysPerCourse() const {
return numDaysPerCourse;
}
But I am getting an error saying:
return value type does not match the function type
I am confused because looking at other questions, this looks like a valid way to do this.
So, how do I return a class member array using a getter in C++?
Upvotes: 2
Views: 209
Reputation: 596958
When I try to compile this code, I get this error:
error: invalid conversion from ‘const int*’ to ‘int*’
This is because GetNumDaysPerCourse()
is const-qualified, so its this
pointer is pointing at a const Student
object, and thus its numDaysPerCourse
member is treated as const
data. You can't assign the address of const data to a pointer-to-non-const (without an explicit type-cast, that is, but don't do that), as that would grant permission for outside code to modify data that is (potentially) stored in read-only memory.
So, you need to either:
const
qualifier from GetNumDaysPerCourse()
:public:
...
int* GetNumDaysPerCourse();
...
private:
...
int numDaysPerCourse[3];
...
};
int* Student::GetNumDaysPerCourse() {
return numDaysPerCourse;
}
GetNumDaysPerCourse()
return a pointer-to-const:public:
...
const int* GetNumDaysPerCourse() const;
...
private:
...
int numDaysPerCourse[3];
...
};
const int* Student::GetNumDaysPerCourse() const {
return numDaysPerCourse;
}
GetNumDaysPerCourse()
is being called on is mutable or read-only:public:
...
int* GetNumDaysPerCourse();
const int* GetNumDaysPerCourse() const;
...
private:
...
int numDaysPerCourse[3];
...
};
int* Student::GetNumDaysPerCourse() {
return numDaysPerCourse;
}
const int* Student::GetNumDaysPerCourse() const {
return numDaysPerCourse;
}
Upvotes: 6
Reputation: 2103
If you don't need to modify the pointer after calling int *GetNumDaysPerCourse() const;
You can modify your class and your implementation as follows:
class Student {
public:
// stuff
const int *GetNumDaysPerCourse() const;
// stuff
private:
//stuff
int numDaysPerCourse[3];
// stuff
};
The .cpp
file:
const int *Student::GetNumDaysPerCourse() const {
return numDaysPerCourse;
}
Upvotes: 2