Object Oriented Programming
in C++
Lecture Slides with Examples and Class Activities
By: Muhammed Jameel
Characteristics of Object-Oriented
Programming
OOP revolves around classes and objects. Its main characteristics:
 Encapsulation: Wrapping data (variables) and methods (functions) together.
• Example: Student data + functions to calculate grade.
 Abstraction: Hiding implementation details and showing only the essential features.
• Example: cout shows output but hides how it works internally.
 Inheritance: Acquiring properties & behaviors of one class into another.
• Example: A Car class can inherit from a Vehicle class.
 Polymorphism: Same function name can behave differently.
• Example: Function overloading, virtual functions.
 Message Passing> Objects communicate with each other by calling methods.
Migration from Modular Programming OOP
→
Modular (C style – structure + function)
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
};
void printStudent(Student s) {
cout << "Name: " << s.name << ", Age: " << s.age << endl;
}
int main() {
Student s1 = {"Ali", 20};
printStudent(s1);
}
Problem: Functions are separate, no direct binding with data.
Object-Oriented (C++ Class + Object)
#include <iostream>
using namespace std;
class Student {
string name; // private by default
int age;
public: // Constructor
Student(string n, int a) {
name = n;
age = a;
}
void printStudent() { // Member Function
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Student s1("Ali", 20); // Object creation
s1.printStudent(); // Function call using object
}
data + functions are bound inside the class.
Implicitly Available Member Functions
in C++
 Even if you don’t define, C++ automatically provides:
 Default Constructor
 Copy Constructor
 Destructor
 Assignment Operator (=)
 Address-of Operator (&)
Defining the Class
#include <iostream>
using namespace std;
class Car {
private:
string color;
int speed;
public:
void setData(string c, int s) { // Member function
color = c;
speed = s; }
void display() { // Member function
cout << "Color: " << color << ", Speed: " << speed << endl;
}
};
int main() {
Car c1; // Object created
c1.setData("Red", 120); // Member function sets data
c1.display(); // Member function displays data
return 0;
}
class ClassName {
private:
// data members
public:
// member functions
};
Using the Class & Creating Objects
class Car {
string model;
int year;
public:
void setData(string m, int y) {
model = m;
year = y;
}
void display() {
cout << "Car: " << model << " (" << year << ")" << endl;
}
};
int main() {
Car c1; // Object creation
c1.setData("Toyota", 2022);
c1.display();
}
Calling Member Functions (Inside vs Outside Class)
 Inside class definition
class Example {
public:
void show() {
cout << "Function defined inside the class" << endl;
}
};
 Outside class definition
class Example {
public:
void show(); // Declaration
};
// Definition outside
void Example::show() {
cout << "Function defined outside the class" << endl;
}
Access Modifiers
class Person {
private:
string name;
public:
void setName(string n) { name = n; }
void showName() { cout << "Name: " << name <<
endl; }
};
•public: Accessible everywhere.
•private: Accessible only within class.
•protected: (used in inheritance).
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
public:
BankAccount(double b) { balance = b; }
void deposit(double amount) { balance += amount; }
void withdraw(double amount) {
if(amount <= balance) balance -= amount;
else cout << "Insufficient funds!" << endl;
}
void showBalance() { cout << "Balance: " << balance << endl; }
};
int main() {
BankAccount acc(1000); // Object
acc.deposit(500);
acc.withdraw(200);
acc.showBalance();
}
Example (Bank Account)
Example (Constructor, Destructor,
Outside Definition)
#include <iostream>
using namespace std;
class Employee {
private:
string name;
int salary;
public:
Employee(string n, int s); // Constructor declaration
~Employee(); // Destructor
void display();
};
// Constructor defined outside
Employee::Employee(string n, int s) {
name = n;
salary = s;
}
// Destructor
Employee::~Employee() {
cout << "Destructor called for " << name <<
endl;
}
// Member function defined outside
void Employee::display() {
cout << "Employee: " << name << ", Salary: " <<
salary << endl;
}
int main() {
Employee e1("Ali", 50000);
e1.display();
}
Class Activities
Activity 1 (Basic):
Create a class Book with attributes title, author, and price. Write member
functions to set and display details.
Activity 2 (Migration):
Write a modular program using struct Student and functions, then convert it into
a class Student.
Activity 3 (Advanced):
Create a BankAccount class with deposit, withdraw, and balance inquiry.
Implement constructors & destructors.
Activity 4 (Access Modifiers):
Make some members private and try accessing them directly (should give error).
Then, access using public functions.
Activity 5 (Team Work):
One student writes a class definition, another implements functions outside the
class, and others test it with objects.
Constructor
A constructor is a special function in a class that is automatically called when an
object is created.
Same name as class.
No return type (not even void).
Used to initialize objects.
class Student {
string name;
int age;
public:
Student() { // Constructor
name = "Unknown";
age = 0;
}
void show() { cout << name << " " << age << endl; }
};
int main() {
Student s; // Constructor is automatically called
s.show();
Types of Constructor
•Default Constructor – No arguments.
•Parameterized Constructor – Takes arguments to initialize.
•Copy Constructor – Creates a copy of another object.
•Programmer-defined Constructor – When you explicitly define any constructor.
•Overloaded Constructor – Multiple constructors with different parameters.
Default Constructor
class Car {
string model;
public:
Car() { model = "Unknown"; } // Default constructor
void display() { cout << "Car: " << model << endl; }
};
Parameterized Constructor
class Car {
string model;
int year;
public:
Car(string m, int y) { // Parameterized constructor
model = m;
year = y;
}
void display() { cout << model << " - " << year << endl; }
};
int main() {
Car c1("Toyota", 2022);
c1.display();
}
Copy Constructor
A copy constructor initializes a new object from an existing
object.
class Student {
string name;
int age;
public:
Student(string n, int a) { name = n; age = a; }
Student(const Student &s) { // Copy Constructor
name = s.name;
age = s.age;
}
void show() { cout << name << " " << age << endl; }
};
int main() {
Student s1("Ali", 20);
Student s2 = s1; // Copy constructor called
s2.show();
}
Destructor
A destructor is called when an object goes out of scope or is explicitly deleted.
Same name as class but with ~.
No parameters, no return type.
class Example {
public:
Example() { cout << "Constructor calledn"; }
~Example() { cout << "Destructor calledn"; }
};
int main() {
Example obj; // Constructor executes here
} // Destructor executes automatically here
Passing Object as Function Arguments
one object can send its data to another object or function
#include <iostream>
using namespace std;
class Box {
int length
public:
Box(int l) { length = l; }
int compare(Box b) {
return length > b.length;
}
};
int main() {
Box b1(10), b2(20);
if (b1.compare(b2)) cout << "b1 is bigger";
else
cout << "b2 is bigger";
}
Returning Object from Member Function
A member function in a class can return an object of the same class
#include <iostream>
using namespace std;
class Box {
int length;
public:
void setLength(int l) {
length = l;
}
int getLength() {
return length;
}
Box add(Box b) {
Box temp; temp.length = length + b.length;
return temp; }
};
int main() {
Box b1, b2, b3;
b1.setLength(10);
b2.setLength(20);
b3 = b1.add(b2);
cout << "Length of Box 1 = " << b1.getLength() <<
endl;
cout << "Length of Box 2 = " << b2.getLength() <<
endl;
cout << "Length of Box 3 (sum) = " <<
b3.getLength() << endl;
return 0;
}
this Pointer
Every object has a hidden pointer this that points to itself.
#include <iostream>
using namespace std;
class Box {
int length;
public:
void setLength(int length) {
this->length = length;
}
void display() {
cout << "Length = " << this->length << endl;
}
};
int main() {
Box b1, b2;
b1.setLength(10);
b2.setLength(25);
b1.display();
b2.display();
return 0;
}
Overloading Constructors
class Person {
string name;
int age;
public:
Person() { name="Unknown"; age=0; } // Default
Person(string n) { name=n; age=0; } // One parameter
Person(string n, int a) { name=n; age=a; } // Two parameters
void show() { cout << name << " - " << age << endl; }
};
int main() {
Person p1, p2("Ali"), p3("Ahmed", 25);
p1.show(); p2.show(); p3.show();
}
Shallow Copy vs Deep Copy
Shallow Copy = copies pointer addresses, not actual data (risk of double deletion).
Deep Copy = copies actual data in new memory.
class Shallow {
int *data;
public:
Shallow(int v) { data = new int(v); }
~Shallow() { delete data; }
};
class Deep {
int *data;
public:
Deep(int v) { data = new int(v); }
Deep(const Deep &d) { data = new int(*d.data); } // Deep copy
~Deep() { delete data; }
};
Constructor’s Initializer List
Used for faster initialization.
class Student {
string name;
int age;
public:
Student(string n, int a) : name(n), age(a) { } // Initializer list
void show() { cout << name << " " << age << endl; }
};
int main() {
Student s("Ali", 20);
s.show();
}
Class Activities
Activity-1:
Create a class Book with title & price. Initialize using both constructors.
Activity-2:
Create a class Employee. Use a copy constructor to copy one object into another.
Activity-3:
Create a class Resource with dynamic memory allocation. Print a message in destructor.
Activity-4:
Create a class Complex (real, imag). Implement addition by passing & returning objects.
Activity-5:
Show how this pointer avoids conflict when constructor parameter name matches data member name.
Activity-6:
Create a Rectangle class with multiple constructors (default, one parameter, two parameters).
Activity-7:
Write a program to demonstrate memory issues in shallow copy, then solve with deep copy.
Any Questions
Thanks

oop_Constructor-De-Constructor-copy-constructor

  • 1.
    Object Oriented Programming inC++ Lecture Slides with Examples and Class Activities By: Muhammed Jameel
  • 2.
    Characteristics of Object-Oriented Programming OOPrevolves around classes and objects. Its main characteristics:  Encapsulation: Wrapping data (variables) and methods (functions) together. • Example: Student data + functions to calculate grade.  Abstraction: Hiding implementation details and showing only the essential features. • Example: cout shows output but hides how it works internally.  Inheritance: Acquiring properties & behaviors of one class into another. • Example: A Car class can inherit from a Vehicle class.  Polymorphism: Same function name can behave differently. • Example: Function overloading, virtual functions.  Message Passing> Objects communicate with each other by calling methods.
  • 3.
    Migration from ModularProgramming OOP → Modular (C style – structure + function) #include <iostream> using namespace std; struct Student { string name; int age; }; void printStudent(Student s) { cout << "Name: " << s.name << ", Age: " << s.age << endl; } int main() { Student s1 = {"Ali", 20}; printStudent(s1); } Problem: Functions are separate, no direct binding with data.
  • 4.
    Object-Oriented (C++ Class+ Object) #include <iostream> using namespace std; class Student { string name; // private by default int age; public: // Constructor Student(string n, int a) { name = n; age = a; } void printStudent() { // Member Function cout << "Name: " << name << ", Age: " << age << endl; } }; int main() { Student s1("Ali", 20); // Object creation s1.printStudent(); // Function call using object } data + functions are bound inside the class.
  • 5.
    Implicitly Available MemberFunctions in C++  Even if you don’t define, C++ automatically provides:  Default Constructor  Copy Constructor  Destructor  Assignment Operator (=)  Address-of Operator (&)
  • 6.
    Defining the Class #include<iostream> using namespace std; class Car { private: string color; int speed; public: void setData(string c, int s) { // Member function color = c; speed = s; } void display() { // Member function cout << "Color: " << color << ", Speed: " << speed << endl; } }; int main() { Car c1; // Object created c1.setData("Red", 120); // Member function sets data c1.display(); // Member function displays data return 0; } class ClassName { private: // data members public: // member functions };
  • 7.
    Using the Class& Creating Objects class Car { string model; int year; public: void setData(string m, int y) { model = m; year = y; } void display() { cout << "Car: " << model << " (" << year << ")" << endl; } }; int main() { Car c1; // Object creation c1.setData("Toyota", 2022); c1.display(); }
  • 8.
    Calling Member Functions(Inside vs Outside Class)  Inside class definition class Example { public: void show() { cout << "Function defined inside the class" << endl; } };  Outside class definition class Example { public: void show(); // Declaration }; // Definition outside void Example::show() { cout << "Function defined outside the class" << endl; }
  • 9.
    Access Modifiers class Person{ private: string name; public: void setName(string n) { name = n; } void showName() { cout << "Name: " << name << endl; } }; •public: Accessible everywhere. •private: Accessible only within class. •protected: (used in inheritance).
  • 10.
    #include <iostream> using namespacestd; class BankAccount { private: double balance; public: BankAccount(double b) { balance = b; } void deposit(double amount) { balance += amount; } void withdraw(double amount) { if(amount <= balance) balance -= amount; else cout << "Insufficient funds!" << endl; } void showBalance() { cout << "Balance: " << balance << endl; } }; int main() { BankAccount acc(1000); // Object acc.deposit(500); acc.withdraw(200); acc.showBalance(); } Example (Bank Account)
  • 11.
    Example (Constructor, Destructor, OutsideDefinition) #include <iostream> using namespace std; class Employee { private: string name; int salary; public: Employee(string n, int s); // Constructor declaration ~Employee(); // Destructor void display(); }; // Constructor defined outside Employee::Employee(string n, int s) { name = n; salary = s; } // Destructor Employee::~Employee() { cout << "Destructor called for " << name << endl; } // Member function defined outside void Employee::display() { cout << "Employee: " << name << ", Salary: " << salary << endl; } int main() { Employee e1("Ali", 50000); e1.display(); }
  • 12.
    Class Activities Activity 1(Basic): Create a class Book with attributes title, author, and price. Write member functions to set and display details. Activity 2 (Migration): Write a modular program using struct Student and functions, then convert it into a class Student. Activity 3 (Advanced): Create a BankAccount class with deposit, withdraw, and balance inquiry. Implement constructors & destructors. Activity 4 (Access Modifiers): Make some members private and try accessing them directly (should give error). Then, access using public functions. Activity 5 (Team Work): One student writes a class definition, another implements functions outside the class, and others test it with objects.
  • 13.
    Constructor A constructor isa special function in a class that is automatically called when an object is created. Same name as class. No return type (not even void). Used to initialize objects. class Student { string name; int age; public: Student() { // Constructor name = "Unknown"; age = 0; } void show() { cout << name << " " << age << endl; } }; int main() { Student s; // Constructor is automatically called s.show();
  • 14.
    Types of Constructor •DefaultConstructor – No arguments. •Parameterized Constructor – Takes arguments to initialize. •Copy Constructor – Creates a copy of another object. •Programmer-defined Constructor – When you explicitly define any constructor. •Overloaded Constructor – Multiple constructors with different parameters. Default Constructor class Car { string model; public: Car() { model = "Unknown"; } // Default constructor void display() { cout << "Car: " << model << endl; } };
  • 15.
    Parameterized Constructor class Car{ string model; int year; public: Car(string m, int y) { // Parameterized constructor model = m; year = y; } void display() { cout << model << " - " << year << endl; } }; int main() { Car c1("Toyota", 2022); c1.display(); }
  • 16.
    Copy Constructor A copyconstructor initializes a new object from an existing object. class Student { string name; int age; public: Student(string n, int a) { name = n; age = a; } Student(const Student &s) { // Copy Constructor name = s.name; age = s.age; } void show() { cout << name << " " << age << endl; } }; int main() { Student s1("Ali", 20); Student s2 = s1; // Copy constructor called s2.show(); }
  • 17.
    Destructor A destructor iscalled when an object goes out of scope or is explicitly deleted. Same name as class but with ~. No parameters, no return type. class Example { public: Example() { cout << "Constructor calledn"; } ~Example() { cout << "Destructor calledn"; } }; int main() { Example obj; // Constructor executes here } // Destructor executes automatically here
  • 18.
    Passing Object asFunction Arguments one object can send its data to another object or function #include <iostream> using namespace std; class Box { int length public: Box(int l) { length = l; } int compare(Box b) { return length > b.length; } }; int main() { Box b1(10), b2(20); if (b1.compare(b2)) cout << "b1 is bigger"; else cout << "b2 is bigger"; }
  • 19.
    Returning Object fromMember Function A member function in a class can return an object of the same class #include <iostream> using namespace std; class Box { int length; public: void setLength(int l) { length = l; } int getLength() { return length; } Box add(Box b) { Box temp; temp.length = length + b.length; return temp; } }; int main() { Box b1, b2, b3; b1.setLength(10); b2.setLength(20); b3 = b1.add(b2); cout << "Length of Box 1 = " << b1.getLength() << endl; cout << "Length of Box 2 = " << b2.getLength() << endl; cout << "Length of Box 3 (sum) = " << b3.getLength() << endl; return 0; }
  • 20.
    this Pointer Every objecthas a hidden pointer this that points to itself. #include <iostream> using namespace std; class Box { int length; public: void setLength(int length) { this->length = length; } void display() { cout << "Length = " << this->length << endl; } }; int main() { Box b1, b2; b1.setLength(10); b2.setLength(25); b1.display(); b2.display(); return 0; }
  • 21.
    Overloading Constructors class Person{ string name; int age; public: Person() { name="Unknown"; age=0; } // Default Person(string n) { name=n; age=0; } // One parameter Person(string n, int a) { name=n; age=a; } // Two parameters void show() { cout << name << " - " << age << endl; } }; int main() { Person p1, p2("Ali"), p3("Ahmed", 25); p1.show(); p2.show(); p3.show(); }
  • 22.
    Shallow Copy vsDeep Copy Shallow Copy = copies pointer addresses, not actual data (risk of double deletion). Deep Copy = copies actual data in new memory. class Shallow { int *data; public: Shallow(int v) { data = new int(v); } ~Shallow() { delete data; } }; class Deep { int *data; public: Deep(int v) { data = new int(v); } Deep(const Deep &d) { data = new int(*d.data); } // Deep copy ~Deep() { delete data; } };
  • 23.
    Constructor’s Initializer List Usedfor faster initialization. class Student { string name; int age; public: Student(string n, int a) : name(n), age(a) { } // Initializer list void show() { cout << name << " " << age << endl; } }; int main() { Student s("Ali", 20); s.show(); }
  • 24.
    Class Activities Activity-1: Create aclass Book with title & price. Initialize using both constructors. Activity-2: Create a class Employee. Use a copy constructor to copy one object into another. Activity-3: Create a class Resource with dynamic memory allocation. Print a message in destructor. Activity-4: Create a class Complex (real, imag). Implement addition by passing & returning objects. Activity-5: Show how this pointer avoids conflict when constructor parameter name matches data member name. Activity-6: Create a Rectangle class with multiple constructors (default, one parameter, two parameters). Activity-7: Write a program to demonstrate memory issues in shallow copy, then solve with deep copy.
  • 25.