Lab Exercise 01
Lab Exercise 01
Objective:
To understand and implement basic Object-Oriented Programming concepts
such as classes, objects, inheritance, polymorphism, and encapsulation in C+
+.
Exercise Steps:
1. Creating a Class and Object:
Task: Define a class Person with the following attributes: name, age, and gender.
Implement a method to display the details of the person.
Explanation: This task introduces the concept of a class and how to create
objects from it. A class is a blueprint for objects, and it can contain attributes
(data members) and methods (member functions).
Code Example:
#include <iostream> // Include the iostream library for input and output
using namespace std; // Use the standard namespace
int main() {
Person person1; // Create an object of the Person class
person1.name = "John Doe"; // Set the name attribute
person1.age = 30; // Set the age attribute
person1.gender = 'M'; // Set the gender attribute
Task: Modify the Person class to make the attributes private and provide
public getter and setter methods.
public:
// Setter method for name
void setName(string n) { name = n; }
// Setter method for age
void setAge(int a) { age = a; }
// Setter method for gender
void setGender(char g) { gender = g; }
int main() {
Person person1; // Create an object of the Person class
person1.setName("John Doe"); // Set the name using the setter method
person1.setAge(30); // Set the age using the setter method
person1.setGender('M'); // Set the gender using the setter method
Task: Create a derived class Student that inherits from Person and adds an
attribute studentID. Implement a method to display the student’s details.
public:
// Setter method for studentID
void setStudentID(int id) { studentID = id; }
// Getter method for studentID
int getStudentID() { return studentID; }
int main() {
Student student1; // Create an object of the Student class
student1.setName("Jane Doe"); // Set the name using the setter method
student1.setAge(20); // Set the age using the setter method
student1.setGender('F'); // Set the gender using the setter method
student1.setStudentID(12345); // Set the student ID using the setter
method
4. Polymorphism:
public:
// Constructor to initialize the radius
Circle(double r) : radius(r) {}
public:
// Constructor to initialize the length and width
Rectangle(double l, double w) : length(l), width(w) {}
int main() {
Shape* shape1 = new Circle(5.0); // Create a Circle object
Shape* shape2 = new Rectangle(4.0, 6.0); // Create a Rectangle object
cout << "Area of Circle: " << shape1->area() << endl; // Display the area
of the circle
cout << "Area of Rectangle: " << shape2->area() << endl; // Display the
area of the rectangle