Student constructor
Create a base class Person with the following member variables: std::string name (public), int age (protected).
Create a derived class Student that adds a member variable: float grade (public).
In the Student class constructor, initialize grade using the initialization list. Then, initialize the name and age member variables inside the constructor's code block.
Make note of how you can't initalize name and age through the member initialization list.
Create a Student object and display its details.
Answer
#include <iostream>
class Person {
public:
std::string name;
protected:
int age;
};
class Student : public Person {
public:
float grade;
Student(std::string n, int a, float g) : grade(g) {
name = n;
age = a;
}
void display_info() {
std::cout << "Name: " << name << "\n";
std::cout << "Age: " << age << "\n";
std::cout << "Grade: " << grade << "\n";
}
};
int main() {
Student student("John Doe", 20, 3.8);
student.display_info();
return 0;
}