I am learning about polymorphism in C++ and am learning about the virtual
function specifier. Since the virtual
specifier forces the program to use the child class's functions, why does it not force the function to use the child class's member variables? Is there a way to do this in C++?
I have tried running the following code with the following classes:
class Student
{
public:
virtual int returnGPA()
{
return gpa;
}
private:
int gpa = 3;
};
class HonorStudent : public Student
{
public:
virtual int returnGPA() override
{
return gpa;
}
private:
int gpa = 4;
};
int main()
{
Student s = Student();
Student h = HonorStudent();
std::cout << s.returnGPA() << std::endl;
std::cout << h.returnGPA() << std::endl;
return 0;
}
I expected the output of the function to be
3
4
but the function outputs
3
3
When I change the declaration of h
to be
HonorStudent h = HonorStudent();
the programs outputs what I initially expected. Any insight would be greatly appreciated.