0% found this document useful (0 votes)
3 views

Lecture2

The document provides an overview of Object-Oriented Programming (OOP) in C++, focusing on the concepts of classes and objects. It explains the structure of a class, including data members and member functions, and illustrates these concepts with examples such as a Student class. Additionally, it discusses the importance of encapsulation, code reusability, and the differences between classes and structures.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture2

The document provides an overview of Object-Oriented Programming (OOP) in C++, focusing on the concepts of classes and objects. It explains the structure of a class, including data members and member functions, and illustrates these concepts with examples such as a Student class. Additionally, it discusses the importance of encapsulation, code reusability, and the differences between classes and structures.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

‫الر ِح ْي ِم‬

َّ ‫الر ْح ٰم ِن‬ ِ ‫ِب ْس ِم‬


َّ ‫هللا‬

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
};

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.

Declaring object of class


Calling member function to work on or operate on the object using dot
Operator.
Defining Class in C++
A class is defined in C++ using the keyword class followed by
the name of the class. The following is the syntax:
class ClassName {
access_specifier:
// Body of the class
};

Here, the access specifier defines the level of access to the


class’s data members.
class ThisClass {
public:
int var; // data member
void print() { // member method
cout << "Hello";
}
};
Defining Class in C++
Case Study: Student Class in C++
• In an educational institute, managing student information efficiently
is crucial. A Student class can be designed in C++ to store and display
student details such as Roll Number and Name.
• When a Student object is created, it holds specific data about an
individual student. The Show() function allows displaying the
student's name. This approach ensures encapsulation and organized
data handling in object-oriented programming.
C++ Implementation
• class Student
• {
• public:
• int Rollno; // Member data
• string name; // Member data

• void Show() // Member function


• {
• cout << "Your name = " << name;
• }
• };
Objects
An object is an instance of a class. When a class is defined, no memory is allocated, but when it is
instantiated (such as when an object is created), memory is allocated.
Declaring an Object:
• When a class is defined, only the specification for the object is defined. No memory or storage is
allocated.
• To use the data and access functions defined in the class, you need to create an object.
Syntax:
ClassName ObjectName;
Access Data Members and Member Functions
– The data members and member functions of a class can be accessed using the dot (.) operator with
an object.
Syntax:
• ObjectName.memberData;
• ObjectName.memberFunction();
Objects
In programming
An object is variable of class type from which it is declared / created.
Each object of class having unique name (follow rules of declaring variable)

As we know an object have characteristics/properties/attributes and behaviors/actions, in C++


or any object oriented programming language the properties of object represented by data
members( the built in data types) and behaviors/action by the member functions.
What is an Object in
C++?
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need
to create objects.
Syntax to Create an Object
We can create an object of the given class in the same way we declare the variables of
any other inbuilt data type.
• ClassName ObjectName;
• MyClass obj;
the object of MyClass with name obj is created.
Case Study: Creating and Using a
Student Object in C++
• In a student management system, data such as student names and roll
numbers need to be stored and accessed efficiently. Using Object-Oriented
Programming (OOP) in C++, a Student class can be designed to handle
student details.
• Once the Student class is defined, an object of this class can be created to
store specific student information. The following case study demonstrates
how to create a Student object, assign values, and display the student's
details.
Scenario
• Ali is a student with roll number 30. We create an object Ob of the Student
class, assign these values, and display them using the Show() function.
C++ Implementation
• #include <iostream> • int main()
• using namespace std; • {
• class Student • Student Ob; // Creating an object
• { • Ob.Rollno = 30; // Assigning roll number
• public: • Ob.name = “Ali"; // Assigning name
• int Rollno; • Ob.Show(); // Displaying the student name
• string name; • return 0;
• void Show() • }
• {
• cout << "Your name = " << name <<
endl;
• }
• };
Class vs. Objects
Class vs. Objects
Why classes are required

It’s about being able to write more efficient and reusable


It is a lot easier, quicker, and more securer to pull out the information
from a class.
Why classes are required
• Encapsulation – Bundles data & functions together, restricting direct access to sensitive data.
• Code Reusability – A class acts as a blueprint, allowing multiple objects to be created without
rewriting code.
• Data Abstraction – Hides complex implementation details and exposes only necessary
functionalities.
• Modularity – Divides the program into smaller, manageable parts, improving organization and
maintainability.
• Security – Protects data using access specifiers (private, public, protected) to control access
levels.
• Maintainability – Easier debugging, updates, and modifications without affecting the entire
program.
• Inheritance Support – Allows code reuse through parent-child relationships, reducing
redundancy.
• Polymorphism Support – Enables different behaviors for the same function name, enhancing
flexibility.
• Scalability – Helps in building large-scale applications by structuring code efficiently.
• Better Memory Management – Classes allow dynamic memory allocation and deallocation,
optimizing resource use.
Write simple class
•#include<iostream>
•using namespace std;
class student{
• private:
• string name;
• int id;
• public:
• set(string N, int ID){
• name = N;
• id = ID; }
string getname(){
• return name;}
• int getid(){
• return id;}
void display(){
• cout<< getname();
• cout<<endl;
• cout<< getid();
• }};
•int main()
•{
• student s1;
• s1.set("Umer Arshad Butt", 51);
• s1.display();
•}
ACCESS SPECIFIERS
In C++, there are three access specifiers:
• public - members are accessible from outside the class
• private - members cannot be accessed (or viewed) from outside the class
• protected - members cannot be accessed from outside the class,
however, they can be accessed in inherited classes.
(In Inheritance we will cover it in detail next lectures).
Accessible within Accessible outside Accessible in
Specifier
class class derived class
private Yes No No
public Yes Yes Yes
Yes (only in
protected Yes No
derived classes)
Working in different files (separate interface and implementation)
file name: main.cpp

•#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.

• The Private information should only be accessible to its owner (object


of particular class).

• Theoretically Information hiding we mean


• “Showing only those details to the outside world which are
necessary for the outside world and hiding all other details
from outside world”.
Advantages of Information
Hiding
1) The advantage of data encapsulation comes when the
implementation of the class changes but the interface remains the
same.

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.

3) Makes maintenance of application easier.

4) Improves the understandability of the application.

5) Thus the concept of encapsulation shows that a non member function


cannot access an object’s private or protected data which provide
Security to data.
Real Life Example of
information Hiding
1- Your Name and your personal information is stored in your brain, we
can not access this information directly. In order to ask your name and
your personal information we need to ask you about your details and it
will be up to you how much information you want to share with us.

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

The meaning of Encapsulation, is to make sure that "sensitive" data


is hidden from users. To achieve this, you must declare class
variables/attributes as private (cannot be accessed from outside the
class).If you want other to read or modify the value of a private
member, you can provide public get and set methods.
Encapsulation
• #include <iostream>
using namespace std;

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 {

• Create a Circle class to calculate • private:


• double radius; // Private variable
and access the area. • public:

• Use public and private access •



Circle(double r) {
radius = r;
specifiers to secure data. • }
• double calculateArea() {
• return 3.1416 * radius * radius;
• }
• };
• int main() {
• Circle c(7); // Creating a Circle object with radius 7
• Circle c1(70);
• cout << "Area of Circle: " << c.calculateArea() << endl;
• return 0;
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 batsman float
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 Activity
// C++ program to demonstrate public
// access modifier

#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;

// accessing public datamember outside class


obj.radius = 5.5;

cout << "Radius is: " << obj.radius << "\n";


cout << "Area is: " << obj.compute_area();
return 0;
}
Output:
Radius is: 5.5
Area is: 94.985

You might also like