#include<iostream> #include<string> using namespace std; class Student { protect
ID: 3625647 • Letter: #
Question
#include<iostream>#include<string>
using namespace std;
class Student
{
protected:
string name;
public:
Student() {name="Default";}
Student(string n) {name=n;}
string get_name(){return name;}
void set_name(string n){name=n;}
void output() {cout<< "Name: " << name << endl;}
};
class GradStudent: public Student
{
protected:
double stipend;
public:
GradStudent(string n, double s);
void output();
};
void process(Student& who);
// outputs the details of the student
int main()
{
Student One("Joe");
GradStudent Two("Susan", 2517.42);
process(One);
process(Two);
return 0;
}
void process(Student& who)
{
who.output();
}
GradStudent::GradStudent(string n, double s)
{
Student();
name = n;
stipend = s;
}
void GradStudent::output()
{
// Hmmm. This should work for Susan, but it doesn't.
cout << "My name is: " << name << " and my stipend is: $" << stipend << endl;
}
Explanation / Answer
I added virtual to the parent class output function so it would properly access the child function
--------------------------------------------------------------
#include <iostream>
#include <string>
using namespace std;
class Student
{
protected:
string name;
public:
Student() {name="Default";}
Student(string n) {name=n;}
string get_name(){return name;}
void set_name(string n){name=n;}
virtual void output() {cout<< "Name: " << name << endl;}
};
class GradStudent: public Student
{
protected:
double stipend;
public:
GradStudent(string n, double s);
void output();
};
void process(Student& who);
// outputs the details of the student
int main()
{
Student One("Joe");
GradStudent Two("Susan", 2517.42);
process(One);
process(Two);
return 0;
}
void process(Student& who)
{
who.output();
}
GradStudent::GradStudent(string n, double s)
{
Student();
name = n;
stipend = s;
}
void GradStudent::output()
{
// Hmmm. This should work for Susan, but it doesn't.
cout << "My name is: " << name << " and my stipend is: $" << stipend << endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.