Oop Unit1
Oop Unit1
Course Outcome
CO1 - Write C++ programs using classes and objects.
Theory Learning Outcome) (TLOs)
TLO 1.1 Compare POP vs OOP approach of programming.
TLO 1.2 Describe the different features of Object-Oriented Programming.
TLO 1.3 Write programs to solve arithmetic expressions.
TLO 1.4 Write programs to demonstrate use of special operators in C++.
TLO 1.5 Develop C++ program to show the use of Classes and Objects
1.1 Procedure Oriented Programming (POP) verses Object Oriented Programming (OOP)
1
Example:
#include <iostream>
using namespace std;
int num1, num2; // Global data
void getData() {
cout << "Enter two numbers: ";
cin >> num1 >> num2;
}
int addNumbers() {
return num1 + num2;
}
int main() {
getData();
int sum = addNumbers();
displayResult(sum);
return 0;
}
A structure is a collection of variables of different data types and member functions under a
single name.
It is similar to a class as both hold a collection of data of different data types.
// Program to assign data to members of a structure variable
#include <iostream>
using namespace std;
struct Person
{
string first_name;
string last_name;
int age;
float salary;
};
int main()
{
Person p1;
cout << "Enter first name: ";
cin >> p1.first_name;
cout << "Enter last name: ";
cin >> p1.last_name;
2
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
return 0;
}
Output:
Enter first name: ABC
Enter last name: pqr
Enter age: 58
Enter salary: 50000
Displaying Information.
First Name: ABC
Last Name: pqr
Age: 58
Salary: 50000
In OOP:
Example:
#include <iostream>
using namespace std;
// Class definition
class Student {
public:
string name;
int roll;
void display() {
cout << "Name: " << name << ", Roll No: " << roll << endl;
3
}
};
int main() {
Student s1; // Object creation
s1.name = "Amit"; // Accessing data
s1.roll = 101;
s1.display(); // Calling member function
return 0;
}
Features Example
Class: class Car
• A class is a blueprint or template for {
creating objects. public:
• It defines data members (variables) string brand;
and member functions (methods). void start() {
cout << "Car is starting..." << endl;
}
};
Object: Car c1;
• An object is an instance of a class. c1.brand = "Tata";
• It has its own copy of the class’s data c1.start();
and can use its functions.
4
• Helps in data hiding and security by void setMarks(int m) {
using access specifiers (private, marks = m;
public, etc.). }
int getMarks() {
return marks;
}
};
Abstraction car.start(); // user doesn't need to know how
• Hides complex details and shows the engine works internally
only the essential features.
• The user doesn’t need to know how
a function works internally.
5
Feature Purpose/Benefit
Class Blueprint for creating objects
Object Instance of a class
Encapsulation Data hiding and protection
Abstraction Hides unnecessary details
Inheritance Reusability and hierarchy
Polymorphism Flexibility and dynamic behavior
Message Passing Communication between objects
Applications of OOP:
• OOP is ideal for GUI-based applications like Windows, Android apps, and web
interfaces. GUI elements (buttons, windows, sliders) can be modeled as objects.
• OOP helps in modeling real-world entities and time-sensitive tasks. Common in
automotive systems, robotics, IoT devices, etc. For example: Embedded software in cars
for speed control, sensor handling, etc.
• Simulation and Modeling-OOP is used to simulate scientific, engineering, or medical
processes. Objects represent physical components or systems. For Example: Flight
simulators, traffic simulation, weather modeling.
• Games are built using objects for players, enemies, scores, levels, etc. OOP makes it easier
to update, extend, and manage game behavior.
• Mobile App Development- Apps use OOP for managing screens, actions, and data. Objects
represent components like buttons, activities, etc.
• Operating Systems and System Software-OOP is used in designing modular parts of OS
like memory managers, schedulers, etc. For example: Windows components (written in
C++), device drivers
• Enterprise Software-Business applications use OOP for managing employees, customers,
billing, etc. For example, ERP systems like SAP, CRM tools like Salesforce.
• Computer-Aided Design/Manufacturing (CAD/CAM)-OOP models complex parts
(objects) and their interactions. For example, AutoCAD, CATIA
• Web frameworks are often built using OOP principles to manage users, sessions, templates,
and routes. For Example, Backend: Django (Python), Laravel (PHP), Spring (Java)
Frontend: React (uses OOP-like component structure)
Data Types:
Data types specify the type of data that a variable can store. Whenever a variable is defined
in C++, the compiler allocates some memory for that variable based on the data type with
which it is declared as every data type requires a different amount of memory.
C++ supports a wide variety of data types, and the programmer can select the data type
appropriate to the needs of the application.
6
Classification of Datatypes
In C++, different data types are classified into the following categories:
S.
No. Type Description Data Types
Basic Data Built-in or primitive data types that are int, float, double,
1 Types used to store simple values. char, bool, void
User Defined Custom data types created by the class, struct, union,
3 Data Types programmer according to their need. typedef, using
int main() {
// Character variable
char c = 'A';
cout << c;
return 0;
}
Output
A
7
cout << x << endl;
// Using hexadecimal base value
x = 0x15;
cout << x;
return 0;
}
Output
25
21
int main() {
Output
1
int main() {
return 0;
}
Output
36.5
8
5. Double Data Type (double)
The double data type is used to store decimal numbers with higher precision. The keyword
used to define double-precision floating-point numbers is double. Its size is 8 bytes (on 64-
bit systems) and can store the values in the range from 1.7e-308 to 1.7e+308
Example:
#include <iostream>
using namespace std;
int main() {
return 0;
}
Output
3.14159
C++ allows us to convert data of one type to that of another. This is known as type conversion.
There are two types of type conversion in C++:
1. Implicit Conversion
2. Explicit Conversion (also known as Type Casting)
Implicit Type Conversion:
The type conversion that is automatically done by the compiler is known as implicit type
conversion. This type of conversion is also known as automatic conversion.
#include <iostream>
using namespace std;
int main() {
int num_int;
double num_double = 9.99;
// implicit conversion
// assigning a double value to an int variable
num_int = num_double;
return 0;
9
}
Output:
num_int = 9
num_double = 9.99
int main() {
// initializing a double variable
double a= 3.56;
cout << "value of a which is in double = " << a << endl;
return 0;
}
Output:
value of a which is in double = 3.56
value of b which is in int = 3
c =3
// printing variable
cout << "Method 1 Variable: " << var1 << endl;
cout << "Method 2 Variable: " << var2 << endl;
cout << "Method 3 Variable: " << var3 << endl;
cout << "Method 4 Variable: " << var4 << endl;
return 0;
}
Output:
class Circle {
float radius;
float area;
public:
void setRadius(float r)
{
radius = r; // dynamically initialized with runtime value
}
void calculateArea() {
area = 3.14 * radius * radius;
cout << "Area of the circle = " << area << endl;
}
};
11
int main() {
float r;
Circle c1;
c1.setRadius(r); // dynamic initialization
c1.calculateArea();
return 0;
}
Output:
Reference variable:
A reference variable is an alias (another name) for an existing variable. It allows you to access
the same memory location with a different name.
Syntax:
datatype &reference_name = original_variable;
Example:
#include <iostream>
using namespace std;
int main() {
int a = 10;
int &ref = a; // ref is a reference to a
cout << "Original value: " << a << endl;
cout << "Reference value: " << ref << endl;
// Modify value using reference
ref = 20;
cout << "After modifying using reference:" << endl;
cout << "Original value: " << a << endl;
cout << "Reference value: " << ref << endl;
return 0;
}
Output:
12
1.4 Special Operators in C++: Scope resolution operator, Memory management
operators, Manipulators
1. Scope Resolution Operator (::)
Used to:
• Access global variables when local variable has the same name.
• Access class static members outside the class.
• Define functions outside class.
Example:
#include <iostream>
using namespace std;
int x = 100; // global variable
int main() {
int x = 50; // local variable
cout << "Local x = " << x << endl;
cout << "Global x = " << ::x << endl; // Scope resolution operator
return 0;
}
Output:
Local x = 50
Global x = 100
Example 1)
#include <iostream>
using namespace std;
int main()
{
int *ptr = new int; // dynamic allocation
*ptr = 25;
cout << "Value = " << *ptr << endl;
delete ptr; // deallocate memory
return 0;
}
Output:
Value = 25
13
Example 2)
# include <iostream>
using namespace std;
int main()
{
// Declared a pointer to store
// the address of the allocated memory
int *nptr;
// Allocate and initialize memory
nptr = new int(6);
// Print the value
cout << *nptr << endl;
// Print the address of memory
// block
cout << nptr;
return 0;
}
Output:
6
0x55f96d7a32b0
int main() {
// Print array
for (int i = 0; i < 5; i++)
cout << nptr[i] << " ";
return 0;
}
Output: 1 2 3 4 5
14
delete Operator
In C++, delete operator is used to release dynamically allocated memory. It deallocates
memory that was previously allocated with new.
Syntax
delete ptr;
where, ptr is the pointer to the dynamically allocated memory.
To free the dynamically allocated array pointed by pointer variable, use the following form of
delete:
delete[] arr;
15
1.5 Structure of C++ program, Basic Input /Output operators and functions in C++,
Simple C++ Program
The C++ program is written using a specific template structure. The structure of the program
written in C++ language is as follows:
Documentation Section:
• This section comes first and is used to document the logic of the program that the
programmer going to code.
• It can be also used to write for purpose of the program.
• Whatever written in the documentation section is the comment and is not compiled
by the compiler.
• Documentation Section is optional since the program can execute without them. Below
is the snippet of the same:
/* This is a C++ program to find the
factorial of a number
Linking Section:
The linking section contains two parts:
Header Files:
• Generally, a program includes various programming elements like built-in functions,
classes, keywords, constants, operators, etc. that are already defined in the
standard C++ library.
• In order to use such pre-defined elements in a program, an appropriate header must
be included in the program.
• Standard headers are specified in a program through the preprocessor
directive #include. In Figure, the iostream header is used. When the compiler processes
the instruction #include<iostream>, it includes the contents of the stream in the
program. This enables the programmer to use standard input, output, and error
facilities that are provided only through the standard streams defined in <iostream>.
These standard streams process data as a stream of characters, that is, data is read and
displayed in a continuous flow. The standard streams defined in <iostream> are listed
here.
#include<iostream>
16
Namespaces:
• A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
• Any user can create separate namespaces of its own and can use them in any other
program.
• In the below snippets, namespace std contains declarations for cout, cin, endl, etc.
statements.
using namespace std;
• Namespaces can be accessed in multiple ways:
o using namespace std;
o using std :: cout;
Definition Section:
• It is used to declare some constants and assign them some value.
• In this section, anyone can define your own datatype using primitive data types.
• In #define is a compiler directive which tells the compiler whenever the message is
found to replace it with “Factorial\n”.
• typedef int INTEGER; this statement tells the compiler that whenever you will
encounter INTEGER replace it by int and as you have declared INTEGER as datatype
you cannot use it as an identifier.
Global Declaration Section:
• Here, the variables and the class definitions which are going to be used in the program
are declared to make them global.
• The scope of the variable declared in this section lasts until the entire program
terminates.
• These variables are accessible within the user-defined functions also.
Function Declaration Section:
• It contains all the functions which our main functions need.
• Usually, this section contains the User-defined functions.
• This part of the program can be written after the main function but for this, write the
function prototype in this section for the function which for you are going to write
code after the main function.
Main Function:
• The main function tells the compiler where to start the execution of the program. The
execution of the program starts with the main function.
• All the statements that are to be executed are written in the main function.
• The compiler executes all the instructions which are written in the curly braces {} which
encloses the body of the main function.
• Once all instructions from the main function are executed, control comes out of the
main function and the program terminates and no further execution occur.
Example:
// Documentation Section
/* This is a C++ program to find the
factorial of a number
The basic requirement for writing this
program is to have knowledge of loops
To find the factorial of a number
iterate over the range from number to 1
*/
17
// Linking Section
#include <iostream>
using namespace std;
// Definition Section
#define msg "FACTORIAL of a NUMBER\n"
typedef int INTEGER;
// Function Section
INTEGER factorial(INTEGER num)
{
// Iterate over the loop from
// num to one
for (INTEGER i = 1; i <= num; i++) {
fact *= i;
}
// Main Function
INTEGER main()
{
// Given number Num
INTEGER Num = 5;
// Function Call
storeFactorial = factorial(Num);
cout << msg;
return 0;
}
Output:
18
• It inserts the contents of variable on the R.H.S. side to the object specified on L.H.S.
Syntax : Cout << variable-name; example : cout<<sum ;
Cout << “string” ; example : cout << “Hello” ;
• The identifier cout is a predefined object that represents the standard output stream.
• Here the standard output stream is Screen.
The statement, cout << “C++ is an Object-Oriented Language.”; causes the specified string
to be displayed on the screen.
Screen Variable OR
Cout <<
String
Standard Input Object Insertion operator
Keyboard Variable
cin >>
Standard Input Object Extraction operator
Comments in C++
Comments are non executable statements. The compiler ignores the comments and do not
execute it.
For single line comments use //
For multi line comments use /* and */
1.6 Class & Object: Introduction, Specifying a class, Access specifiers, Defining member
functions: Inside class and Outside class, Creating objects, Memory allocations for
objects
C++ Classes
A class is a user-defined data type, which holds its own data members and member functions
that can be accessed and used by creating an instance of that class. A C++ class is like a
blueprint for an object.
For example, Student Class
We can have many students with different names, roll numbers, and marks, but they all share
common properties and actions.
🔹 Common Attributes (Data Members):
• Name
• Roll Number
19
•Marks
•Grade
🔹 Common Behaviors (Member Functions):
• Input details
• Display details
• Calculate grade
Syntax: Example:
class class-name Class student
{ {
private : private :
variable declarations; int rollno; // data member
function declarations; char name[30]; // data member
public: public:
variable declarations; void getdata (void); // member function
function declarations; void showdata(void); // member function
}; };
// Class definition
class Circle {
public:
double radius;
double compute_area() {
return 3.14*radius*radius;
}
20
};
int main() {
Circle obj;
return 0;
}
Output
Radius is: 5.5
Area is: 94.98
In the above program, the data member radius is declared as public so it could be accessed
outside the class and thus was allowed access from inside main(). Same with the member
function compute_area(). If we do not specify any access modifiers for the members inside the
class, then by default the access modifier for the members will be Private.
2. Private Specifier
The class members declared as private can be accessed only by the member functions inside
the class. They are not allowed to be accessed directly by any object or function outside the
class. Only the member functions or the friend functions/ friend class are allowed to access the
private data members of the class.
Example:
#include<iostream>
using namespace std;
class Circle {
// private members
private:
double radius;
double compute_area() {
};
int main() {
Circle obj;
return 0;
}
Output
main.cpp: In function ‘int main()’:
main.cpp:22:9: error: ‘double Circle::radius’ is private within this context
22 | obj.radius = 1.5;
| ^~~~~~
main.cpp:7:16: note: declared private here
7| double radius;
| ^~~~~~
main.cpp:23:43: error: ‘double Circle::compute_area()’ is private within this context
23 | cout << "Area is:" << obj.compute_area();
| ~~~~~~~~~~~~~~~~^~
main.cpp:8:17: note: declared private here
8| double compute_area() {
The output of the above program is a compile time error because we are not allowed to access
the private data members of a class directly from outside the class. Yet an access to obj.radius
is attempted, but radius being a private data member, we obtained the above compilation
error.
How to Access Private Members?
The standard way to access the private data members of a class is by using the public member
functions of the class. The function that provides the access is called getter method and the
function that updates the value is called the setter method.
Example:
#include<iostream>
using namespace std;
class Circle {
// private members
private:
double radius;
public:
double compute_area() {
return 3.14*radius*radius;
}
};
int main() {
Circle obj;
return 0;
}
Output
Radius is: 1.5
Area is: 7.065
3. Protected Specifier
The protected access modifier is similar to the private access modifier in the sense that it can't
be accessed outside of its class unless with the help of a friend class. The difference is that the
class members declared as Protected can be accessed by any subclass (derived class) of that
class as well.
Example:
#include <bits/stdc++.h>
using namespace std;
// base class
class Parent {
protected:
int id_protected;
};
int getId() {
23
return id_protected;
}
};
int main() {
Child obj1;
obj1.setId(81);
cout << "ID: " << obj1.getId();
return 0;
}
Output
ID: 81
The membership label ‘class-name:: ‘ tells the compiler that the function belongs to the
spiffed class.
• The symbol :: is called scope resolution operator.
Example:
24
public:
// Constructor
void getdata(int l, int b)
{
length = l;
breadth = b;
}
int rectangle::perimeter()
{
return 2 * (length + breadth);
}
int main()
{
// Creating object
rectangle r;
r.getdata(2, 3);
cout << "perimeter: " << r.perimeter() << endl;
cout << "area: " << r.area() << endl;
return 0;
}
Output:
25
2) Defining member function inside the class definition:
In this, the function declaration is replaced by the function definition.
// C++ program for Inside Class Definition
#include <iostream>
using namespace std;
class rectangle
{
private:
int length;
int breadth;
public:
void getdata(int l, int b)
{
length = l;
breadth = b;
}
// area() function inside class
int area() { return (length * breadth); }
// perimeter() function outside class
int perimeter() { return 2 * (length + breadth); }
};
int main()
{
// Creating object
rectangle r;
r.getdata(2, 3);
cout << "perimeter: " << r.perimeter() << endl;
cout << "area: " << r.area() << endl;
return 0;
}
Output:
perimeter: 10
area: 6
26
Assignment no:01
Issue date: 09/07/2025
Submission date: 18/07/2025
1. Declare a structure ‘book’ having data member’s title, author and price. Accept and
display data for one variable.
2. Declare a structure ‘account’ having data member’s account_no and balance. Accept
and display data for 5 variables.
3. Declare a structure ‘Employee’ having data members emp_id and emp_name and
basic_salary. Accept this data for 5 variables and display the details of employee having
salary > 5000.
4. Write a C++ program to create a class Circle with private data member radius. Define
member functions area() and circumference() inside the class.
5. Write a C++ program to create a class Circle with private data member radius. Define
member functions area() and circumference() outside the class using the scope
resolution operator.
6. Create a class Student with data members name and marks. Define functions display()
and grade() inside the class.
7. Create a class Student with data members name and marks. Define functions display()
and grade() outside the class.
8. Design a class BankAccount with data members name and balance. Write functions
deposit() and display() inside the class.
9. Design a class BankAccount with data members name and balance. Define deposit()
and display() outside the class.
10. Compare class and object.
27