Object-Oriented
Programming (OOP) in
C++
Prepared By: Abdullah Emam
Sec 3&4
Introduction to OOP
What is OOP?
•
Object-Oriented Programming (OOP) is a programming paradigm based on the
concept of "objects.“
•
Objects contain data (attributes) and functions (methods).
•
Provides better modularity, code reusability, and security.
Benefits of OOP
Code reusability through inheritance
Better data security with encapsulation
Easier maintenance and debugging
Improved productivity in software
development
Key Concepts of OOP
Encapsulation
Abstraction
Inheritance
Polymorphism
What is Encapsulation?
Wrapping data (variables) and code
(functions) into a single unit (class).
Protects data from direct access.
Provides getter and setter methods.
Example of Encapsulation
#include <iostream>
using namespace std;
class Student {
private:
int age;
public:
void setAge(int a) { age = a; }
int getAge() { return age; }
};
int main() {
Student s;
s.setAge(20);
cout << "Age: " << s.getAge() << endl;
return 0;
}
What is Abstraction?
Hiding implementation details and only
showing essential features.
Achieved using abstract classes and
interfaces.
Example of Abstraction
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() = 0; // Pure virtual
function
};
class Circle : public Shape {
public:
void draw() override { cout << "Drawing
Circle" << endl; }
};
int main() {
Shape* shape = new Circle();
shape->draw();
delete shape;
return 0;
}
What is Inheritance?
Creating a new class from an existing class.
Promotes code reuse and hierarchical
relationships.
Types:
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Example of Single Inheritance
#include <iostream>
using namespace std;
class Parent {
public:
void show() { cout << "This is Parent class"
<< endl; }
};
class Child : public Parent {};
int main() {
Child obj;
obj.show();
return 0;
}
What is Polymorphism?
Same function name, different behaviors.
Achieved through:
Function Overloading
Operator Overloading
Function Overriding (Runtime Polymorphism)
Example of Function Overloading
#include <iostream>
using namespace std;
class Math {
public:
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
};
int main() {
Math obj;
cout << obj.add(5, 10) << endl;
cout << obj.add(3.5, 2.5) << endl;
return 0;
}
access specifiers
private, public, and protected in C++
In C++ Object-Oriented Programming (OOP), access specifiers
(private, public, and protected) define the visibility of
class members (attributes and methods) within and outside
the class.
1. private Access Specifier
Members declared private are accessible only inside the
same class.
Cannot be accessed directly from outside the class.
Used for data encapsulation (hiding data from outside
access).
Example of private Members
#include <iostream>
using namespace std;
class Student {
private:
string name; // Private member (cannot be accessed outside the
class)
public:
// Constructor to set the name
void setName(string n) {
name = n;
}
// Function to get the name
string getName() {
return name;
}
};
int main() {
Student s1;
// s1.name = "John";
ERROR: Cannot
access private member
s1.setName("John"); //
Allowed because
it's a public function
cout << "Student Name: " << s1.getName() <<
endl;
return 0;
}
2. public Access Specifier
Members declared public are accessible anywhere (inside and outside the
class).
Used for functions or variables that should be accessible freely.
#include <iostream>
using namespace std;
class Student {
public:
string name;
// Public member (can be accessed from anywhere)
void display() {
cout << "Student Name: " << name << endl;
}
};
int main() {
Student s1;
s1.name = "Alice";
s1.display();
return 0;
}
//
Allowed (public)
3. protected Access Specifier
protected members are similar to private, but
they can also be accessed in derived (child)
classes.
Cannot be accessed directly outside the class
(like private).
Can be accessed inside derived classes (unlike
private).
Example of protected Members
#include <iostream>
using namespace std;
class Person {
int main() {
protected:
Student s1;
string name; // Protected member (not
// s1.name = "Bob";
ERROR: Cannot
accessible outside, but accessible in derived
access protected member directly
class)
s1.setName("Bob"); //
Allowed through
public:
public function
void setName(string n) {
s1.display();
name = n;
return 0;
}
}
};
// Derived class (inherits from Person)
class Student : public Person {
public:
void display() {
cout << "Student Name: " << name << endl;
//
Allowed (inherited from Person)
}
};
Key Differences:
Access Modifier
Accessible Inside
Class?
Accessible Outside
Class?
Accessible in
Derived Class?
public
Yes
Yes
Yes
protected
Yes
No
Yes
private
Yes
No
No
What is a Constructor?
A constructor is a special member function of a class that automatically
gets called when an object of the class is created. It is used to initialize
an object.
Characteristics of Constructors:
The constructor has the same name as the class.
It does not return a value, not even void.
It is automatically invoked when an object is created.
It can have parameters (Parameterized Constructor).
It can be overloaded (Multiple constructors with different arguments).
Types of Constructors in C++
Default Constructor (No parameters)
Parameterized Constructor (Takes arguments)
Copy Constructor (Copies another object)
Destructor (Handles cleanup)
Example: Default Constructor
#include <iostream>
using namespace std;
class Student {
public:
// Default constructor
Student() {
cout << "Constructor Called! Object
Created.\n";
}
};
int main() {
Student s1; // Constructor is called
automatically
return 0;
}
Example: Parameterized Constructor
A Parameterized Constructor allows passing values while creating an object
class Student {
private:
string name;
int age;
public:
// Parameterized Constructor
Student(string n, int a) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;}
};
int main() {
Student s1("Alice", 21);
s1.display();
Student s2("Bob", 22);
s2.display();
return 0;
}
Name: Alice, Age: 21
Name: Bob, Age: 22
Example: Copy Constructor
A Copy Constructor creates a new object by copying an existing object.
class Student {
private:
string name;
public:
// Parameterized Constructor
Student(string n) {
name = n;}
// Copy Constructor
Student(const Student &s) {
name = s.name;}
void display() {
cout << "Student Name: " << name << endl;}
};
int main() {
Student s1("John");
Student s2 = s1; // Copy constructor is called
s1.display();
s2.display();
return 0;
}
Student Name: John
Student Name: John
2. What is a Destructor?
A Destructor is a special member function that automatically gets
called when an object is destroyed. It is used to free resources
(like memory, file handles, etc.).
Characteristics of Destructors:
Has the same name as the class, prefixed with ~.
No return type and no parameters.
Only one destructor per class (cannot be overloaded).
Called automatically when the object goes out of scope or is
deleted.
Example: Destructor in C++
#include <iostream>
using namespace std;
Constructor: Object Created
class Student {
Destructor: Object Destroyed
public:
// Constructor
Student() {
cout << "Constructor: Object Created\n";
}
// Destructor
~Student() {
cout << "Destructor: Object Destroyed\n";
}
};
int main() {
Student s1; // Constructor is called automatically
return 0;
// Destructor is called automatically when `s1`
goes out of scope
}
Practical Implementation
A Full Project (Student Management System in
C++)
A class for Student
Functions for adding, removing, and displaying
students.
Uses OOP principles like encapsulation,
inheritance, and polymorphism.
Student Management System implemented in C++
using OOP principles like encapsulation,
inheritance, and polymorphism. It includes:
A Student class (encapsulation)
Functions to add, remove, and display students
Inheritance (GraduateStudent derived from
Student)
Polymorphism (using virtual functions)
class Student
#include <iostream>
#include <string>
using namespace std;
// Maximum number of students
const int MAX_STUDENTS = 100;
// Base class: Student
class Student {
protected:
string name;
int id;
int age;
public:
// Constructor
Student() : id(0), age(0), name("") {} //
Default constructor
Student(string n, int i, int a) : name(n),
id(i), age(a) {}
// Virtual function for polymorphism
virtual void display() const {
cout << "ID: " << id << ", Name: " << name
<< ", Age: " << age << endl;
}
// Getter for ID
int getId() const {
return id;
}
// Virtual Destructor
virtual ~Student() {}
};
class GraduateStudent
// Derived class: GraduateStudent (inherits from Student)
class GraduateStudent : public Student {
private:
string researchTopic;
public:
GraduateStudent() : Student(), researchTopic("") {}
GraduateStudent(string n, int i, int a, string topic)
: Student(n, i, a), researchTopic(topic) {}
// Overriding display function (Polymorphism)
void display() const override {
cout << "ID: " << id << ", Name: " << name << ", Age: " << age
<< ", Research Topic: " << researchTopic << endl;
}
};
class StudentManagementSystem
// Student Management System class
class StudentManagementSystem {
private:
Student* students[MAX_STUDENTS]; // Array of pointers
int count; // Number of students
public:
// Constructor
StudentManagementSystem() : count(0) {}
// Destructor (frees allocated memory)
~StudentManagementSystem() {
for (int i = 0; i < count; i++) {
delete students[i];
}
}
Function to add a new student
void addStudent() {
if (count >= MAX_STUDENTS) {
if (type == 2) { // Graduate Student
cout << "Student list is full!\n";
cout << "Enter Research Topic: ";
return;
getline(cin, topic);
}
students[count] = new
string name, topic;
GraduateStudent(name, id, age, topic);
int id, age, type;
} else { // Regular Student
cout << "\nEnter Student Type (1:
students[count] = new
Regular, 2: Graduate): ";
Student(name, id, age);
cin >> type;
}
cin.ignore(); // Ignore newline
cout << "Enter ID: ";
cin >> id;
cin.ignore();
cout << "Enter Name: ";
getline(cin, name);
cout << "Enter Age: ";
cin >> age;
cin.ignore();
count++;
cout << "Student added
successfully!\n";
}
Function to remove a student by
to remove a student by ID
ID // Function
void removeStudent() {
int id;
cout << "\nEnter Student ID to remove: ";
cin >> id;
for (int i = 0; i < count; i++) {
if (students[i]->getId() == id) {
delete students[i]; // Free memory
for (int j = i; j < count - 1; j++) {
students[j] = students[j + 1]; //
Shift elements left
}
count--;
cout << "Student removed successfully!\n";
return;
}
}
cout << "Student not found!\n";
}
Function to display all students
void displayStudents() const {
cout << "\n--- Student List --\n";
if (count == 0) {
cout << "No students in the
system.\n";
return;
}
for (int i = 0; i < count; i++) {
students[i]->display();
}
}
};
Main function
int main() {
StudentManagementSystem sms;
int choice;
while (true) {
cout << "\nStudent
Management System Menu:\n";
cout << "1. Add Student\n";
cout << "2. Remove
Student\n";
cout << "3. Display
Students\n";
cout << "4. Exit\n";
cout << "Enter your choice:
";
cin >> choice;
switch (choice) {
case 1:
sms.addStudent();
break;
case 2:
sms.removeStudent();
break;
case 3:
sms.displayStudents();
break;
case 4:
cout << "Exiting...\n";
return 0;
default:
cout << "Invalid choice! Try
again.\n";
}
}
}
Sheet
1. Write a C++ program to implement a class called Circle that has
private member variables for radius. Include member functions to
calculate the circle's area and circumference.
2. Write a C++ program to create a class called Rectangle that has
private member variables for length and width. Implement member
functions to calculate the rectangle's area and perimeter.
3. Write a C++ program to create a class called Person that has private
member variables for name, age and country. Implement member
functions to set and get the values of these variables.
4. Write a C++ program to create a class called Car that has private
member variables for company, model, and year. Implement member
functions to get and set these variables.
Sheet
5. Write a C++ program to implement a class called BankAccount that
has private member variables for account number and balance. Include
member functions to deposit and withdraw money from the account.
6. Write a C++ program to create a class called Triangle that has private
member variables for the lengths of its three sides. Implement member
functions to determine if the triangle is equilateral, isosceles, or scalene.
7. Write a C++ program to implement a class called Employee that has
private member variables for name, employee ID, and salary. Include
member functions to calculate and set salary based on employee
performance.
Sheet
8. Write a C++ program to implement a class called Date that has
private member variables for day, month, and year. Include
member functions to set and get these variables, as well as to
validate if the date is valid.
9. Write a C++ program to implement a class called Student that
has private member variables for name, class, roll number, and
marks. Include member functions to calculate the grade based on
the marks and display the student's information.
10. Write a C++ program to implement a class called Shape with
virtual member functions for calculating area and perimeter.
Derive classes such as Circle, Rectangle, and Triangle from the
Shape class and override virtual functions accordingly.
Thank You
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )