Lecture2
Lecture2
Object-Oriented Programming
(OOP)
Class & Object
Lecturer: Mr. Muhammad Amjad Raza
Email: [email protected]
[email protected]
Call/WhatsApp: 03456762672
What is a Class in C++?
A class in C++ is the building block that leads to object-oriented
programming.
• A class is a user-defined data type that holds its own data members
(Variable) and member functions, which can be accessed and used by
creating an instance of that class.
• A C++ class is like a blueprint for an object.
• A class is a user-defined data type that has data members and
member functions.
• Class is Collection of objects like Fruits is class and Banana, Apple,
Mango etc. are objects.
Syntax
keyword User Defined Name
class ClassName
{
Access Specifier: // Can be private, public, or protected
Data Members; // Variables to be used
Member functions() // Methods to access data members
{
Body of function;
}
}; // Class name ends with a semicolon
What is a Class in C++?
• A class is a user-defined data type, which holds its own data members and
member functions, which can be accessed and used by creating an instance of
that class. A C++ class is like a blueprint for an object.
• For Example: Consider the Class of Cars. There may be many cars with different
names and brands but all of them will share some common properties like all of
them will have 4 wheels, Speed Limit, Mileage range, etc. So here, the Car is the
class, and wheels, speed limits, and mileage are their properties.
• A Class is a user-defined data type that has data members and member functions.
• Data members are the data variables and member functions are the functions used to
manipulate these variables together, these data members and member functions define
the properties and behaviour of the objects in a Class.
• In the above example of class Car, the data member will be speed limit, mileage, etc, and
member functions can be applying brakes, increasing speed, etc.
• Note: When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
Class structure
Defining a class
class class_name
{
body of class/definition of class
};
1- Data members
(Data items used to represent attributes/characteristics/properties of an object)
2-Member functions/methods
Functions used to work on its data members are called member functions or methods.
•#include<iostream>
•#include "import.h"
using namespace std;
int main()
•{
• student s1;
• s1.setname("Umer Arshad Butt");
• s1.setroll(51);
• s1.setmark(100);
• cout<<s1.getname();
• cout<<"\n";
• cout<<s1.getroll();
• cout<<"\n";
• cout<<s1.getmarks();
•}
Working in different files (separate interface and implementation)
import header file name: import.h
using namespace std;
class student{
private:
string student_name;
int roll_no;
float marks;
public:
void setname(string N)
{
student_name = N;
}
void setroll(int R)
{
roll_no = R;
}
void setmark(float M)
{
marks = M;
}
string getname()
{
return student_name;
}
int getroll()
{
return roll_no;
}
int getmarks()
{
return marks;
}
};
Class Activity
Private Members Type
Batcode (4 digit), Total_innings, Integer
n_out_innings, runs, bestscore
batavg float
batname 10 character
Calavg() (Function to compute float
batsman avegerage )
Public Member:
readdata() void
detail: Function to accept
value from Batcode, name,
innings, not_out and invoke the
function Calcavg()
displaydata() Void
Detail: Function to display the
data members on the screen
Class UML Diagram
Difference between classes
and structures
• Technically speaking, structs and classes are almost equivalent
• The major difference like class provides the flexibility of combining data and
methods (functions ) and it provides the re-usability called inheritance.
• A class has all members private by default. A struct is a class where members
are public by default
Difference between classes
and structures
• // Program 1
• #include <stdio.h>
• struct Test {
• int x; // x is public
• };
• int main()
• {
• Test t;
• t.x = 20; // works fine because x is public getchar();
• return 0;
• }
Difference between classes and
structures
Feature Class Structure
Default Access Modifier Private Public
Encapsulation Supports full encapsulation (data hiding) Limited encapsulation (default public access)
Data Security More secure due to private members Less secure as members are public by default
Does not support inheritance (in C, but
Inheritance Supports inheritance
supports in C++)
Polymorphism Supports polymorphism Does not support polymorphism
Use Case Used for Object-Oriented Programming (OOP) Used for lightweight data grouping
Can have member functions but mostly used
Member Functions Can have both member functions and data members
for data storage
Memory Management More controlled memory allocation Simple memory allocation
Constructor & Destructor Supports constructors & destructors Supports them in C++, but not in C
By Default, Behavior More suitable for complex structures with behavior Best for simple data structures
Difference between classes
and structures
• // Program 2
• #include <iostream.h>
• class Test {
• int x; // x is private
• };
• int main()
• {
• Test t;
• t.x = 20; // compiler error because x is private
• getchar(); return 0;
• }
Class Template
• A template is a simple yet very powerful tool in
C++.
• The simple idea is to pass data type as a
parameter so that we don’t need to write the
same code for different data types
Class Template
#include<iostream>
using namespace std;
template<class template_name>
class calculator
{
private:
template_name number1;
template_name number2;
template_name number3;
public:
set(template_name N1, template_name N2, template_name N3)
{
number1 = N1;
number2 = N2;
number3 = N3;
}
template_name add()
{
return number1+number2+number3;
}
};
int main()
{
calculator <int> object1;
object1.set(100,200,300);
cout<<object1.add();
}
Class template with multiple arguments
#include<iostream>
using namespace std;
// class template with multiple parameters
template<class template_name, class template_name2, class template_name3>
class calculator
{
private:
template_name number1; int main()
template_name2 number2; {
template_name3 number3; calculator <int, string, float> object_creation;
public:
set(template_name N1, template_name2 N2, template_name3 N3) object_creation.set(100, "Umer But", 200.303);
{
number1 = N1; cout<<object_creation.numberdisplay();
number2 = N2; cout<< "\n" <<
object_creation.number2display();
number3 = N3;
cout<< "\n"
}
<<object_creation.number3display();
template_name numberdisplay()
{
}
return number1;
}
template_name2 number2display()
{
return number2;
}
template_name3 number3display()
{
return number3;
}
};
Encapsulation /
Information Hiding/ Data
Hiding
• Information hiding is one of the most important principles of OOP
inspired from real life which says that all information should not be
accessible to all persons.
2) It is used to reduce the human errors. The data and function are
bundled inside the class that take total control of maintenance and thus
human errors are reduced.
2- No one can access the information/ contacts of your cell phone if you
locked memory of your cell phone with some password.
3- While you login to your email, you must need to provide the hidden
information (Password) to your server.
Encapsulation
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
Case Study: Implementation of Encapsulation
in Cylinder and Circle Classes
A manufacturing company needs a software system to manage geometric shapes for its design
process. Two critical shapes are Cylinders and Circles, which are used in various components. The
company requires functionalities to calculate the volume of a cylinder and the area of a circle,
ensuring data security and encapsulation.
To achieve this, we create two classes:
• Cylinder Class → Encapsulates volume calculation and protects volume
data.
• Circle Class → Implements access specifiers to calculate and retrieve the
area.
Case 1: Cylinder Class with
Encapsulation
Objective:
• Create a Cylinder class with private data members.
• Encapsulate the function that calculates the volume.
• Protect the volume variable from direct access.
Implementation:
• #include <iostream>
• using namespace std;
• class Cylinder { • int main() {
• private: • Cylinder c(5, 10); // Creating object with radius 5 and
• double radius, height;
height 10
• double volume; // Private variable to protect from outside access • c.displayVolume(); // Displaying calculated volume
• void calculateVolume() { • return 0;
• volume = 3.1416 * radius * radius * height; • }
• }
• public:
• Cylinder(double r, double h) {
• radius = r;
• height = h;
• calculateVolume(); // Private function called internally
• }
• void displayVolume() {
• cout << "Volume of Cylinder: " << volume << endl;
• }
• };
Case 2: Circle Class Using Access Specifiers
• #include <iostream>
• using namespace std;
Objective: • class Circle {
#include<iostream>
using namespace std;
// class definition
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
// main function
int main()
{
Circle obj;