Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include <iostream>

#include <vector>
#include <string>

class Student {
public:
Student(std::string name, int age) : name(name), age(age) {}

virtual void display() const {


std::cout << "Name: " << name << ", Age: " << age;
}//The virtual keyword indicates that this function can be overridden in
derived classes.

virtual void study() const = 0; // Pure virtual function to study

protected:
std::string name;
int age;
};

class Undergraduate : public Student {


public:
Undergraduate(std::string name, int age, std::string major)
: Student(name, age), major(major) {}

void display() const override {


Student::display();
std::cout << ", Major: " << major << std::endl;
}

void study() const override {


std::cout << "Undergraduate student is studying." << std::endl;
}

private:
std::string major;
};

class Graduate : public Student {


public:
Graduate(std::string name, int age, std::string researchArea)
: Student(name, age), researchArea(researchArea) {}

void display() const override {


Student::display();
std::cout << ", Research Area: " << researchArea << std::endl;
}

void study() const override {


std::cout << "Graduate student is conducting research." << std::endl;
}

private:
std::string researchArea;
};

int main() {
std::vector<Student*> students;
// Create instances of students
Undergraduate undergrad("John", 20, "Computer Science");
Graduate grad("Alice", 25, "Machine Learning");

// Add students to the vector


students.push_back(&undergrad);
students.push_back(&grad);

// Display and let students study using polymorphism


for (const auto& student : students) {
student->display();
student->study();
std::cout << "-------------------------" << std::endl;
}

return 0;
}

You might also like