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:
- drop the
const qualifier from GetNumDaysPerCourse():
public:
...
int* GetNumDaysPerCourse();
...
private:
...
int numDaysPerCourse[3];
...
};
int* Student::GetNumDaysPerCourse() {
return numDaysPerCourse;
}
- make
GetNumDaysPerCourse() return a pointer-to-const:
public:
...
const int* GetNumDaysPerCourse() const;
...
private:
...
int numDaysPerCourse[3];
...
};
const int* Student::GetNumDaysPerCourse() const {
return numDaysPerCourse;
}
- combine the two approaches to provide both const and non-const access to the same array, depending on whether the object that
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;
}
error: invalid conversion from ‘const int*’ to ‘int*’ [-fpermissive] return numDaysPerCourse;is the error I see since it wasn't included in the question.std::array<int, 3>for the array, and return either by constant reference or by value.