0% found this document useful (0 votes)
55 views27 pages

Oop Unit1

The document outlines the principles of Object-Oriented Programming (OOP) in C++, comparing it to Procedure-Oriented Programming (POP) and detailing key features such as classes, objects, encapsulation, and inheritance. It also covers data types, type compatibility, variable declaration, and initialization, along with examples of C++ code. Additionally, it highlights the applications of OOP in various fields, including software development, simulation, and enterprise applications.

Uploaded by

manasdipakkhadke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views27 pages

Oop Unit1

The document outlines the principles of Object-Oriented Programming (OOP) in C++, comparing it to Procedure-Oriented Programming (POP) and detailing key features such as classes, objects, encapsulation, and inheritance. It also covers data types, type compatibility, variable declaration, and initialization, along with examples of C++ code. Additionally, it highlights the applications of OOP in various fields, including software development, simulation, and enterprise applications.

Uploaded by

manasdipakkhadke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Unit - I Principles of Object-Oriented Programming

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

Unit - I Principles of Object Oriented Programming


1.1 Procedure Oriented Programming (POP) verses Object Oriented Programming (OOP)
1.2 Features of Object Oriented Programming, Examples of Object-Oriented languages,
Applications of OOP
1.3 Data types, Type compatibility, Declaration of variable, Dynamic initialization of variable,
Reference variable, Type casting
1.4 Special Operators in C++: Scope resolution operator, Memory management operators,
Manipulators
1.5 Structure of C++ program, Basic Input /Output operators and functions in C++, Simple
C++ Program
1.6 Class & Object: Introduction, Specifying a class, Access specifiers, Defining member
functions: Inside class and Outside class, Creating objects, Memory allocations for objects
_________________________________________________________________________________________________

1.1 Procedure Oriented Programming (POP) verses Object Oriented Programming (OOP)

Procedure-Oriented Programming (POP):


POP is a programming approach where the focus is on functions (procedures) that operate on
data. It follows a top-down structure, meaning you start with the problem and divide it into
smaller sub-problems (functions).
In POP:
• A program is divided into small parts called functions.
• Data is often shared globally among these functions. Less secure, as global data can
be accessed anywhere.
• It follows a top-down approach — the program is designed from the main function
and broken down into smaller tasks.
• Data moves freely between functions.
• Examples: C, Pascal, FORTRAN.

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

void displayResult(int result) {


cout << "Sum is: " << result << endl;
}

int main() {
getData();
int sum = addNumbers();
displayResult(sum);
return 0;
}

POP is good for... But not good for...


Small, simple programs Large or complex projects
Fast development Reusability, data security, and maintenance
Beginners to understand basic programming Real-world modeling and secure data handling

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;

cout << "\nDisplaying Information." << endl;


cout << "First Name: " << p1.first_name << endl;
cout << "Last Name: " << p1.last_name << endl;
cout << "Age: " << p1.age << endl;
cout << "Salary: " << 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

Object-Oriented Programming (OOP):


Object-Oriented Programming (OOP) is a programming approach that focuses on objects
— real-world entities that contain both data and functions.

In OOP:

• A program is divided into classes and objects.


• It models real-world problems using data + behavior together.
• Data is protected using encapsulation.
• It follows a bottom-up approach, making development modular, secure, and reusable.
• Examples: C++, Java, Python.

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

Procedural Oriented Programming Object Oriented programming


It follows top-down approach in program It follows bottom-up approach in program
design design
It emphasis on procedure rather than data It emphasis on data rather than procedure.
Larger programs are divided into smaller Programs are divided into Objects.
programs known as functions.
Here most of the data is global and data is Data is hidden and cannot be accesses by
not hidden and can be accessed by external external functions.
functions.
New data cannot be easily created whenever New data and functions can be easily
necessary. It does not model the real-world. created whenever necessary. It models the
real-world very well.
Example is C , Fortran ,COBOL Example C++ , Java

1.2 Features of Object Oriented Programming, Examples of Object Oriented languages,


Applications of OOP

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.

Encapsulation class Student


• It is the process of wrapping data {
and functions together into a single private:
unit (class). int marks; // hidden data
public:

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.

Inheritance class Car


• Allows one class to inherit the {
properties and behavior of another public:
class. void start()
• Promotes code reusability. {
cout << "Car is starting..." << endl;
}
};
// Derived class
class SportsCar : public Car {
public:
void boost() {
cout << "SportsCar is boosting speed!"
<< endl;
}
};
Polymorphism void show(int x)
• Means “many forms”. {
• A single function or operator cout << "Integer: " << x;
behaves differently based on input or }
object. void show(float x)
Types: {
• Function Overloading (same function cout << "Float: " << x;
name, different parameters) }
• Operator Overloading // function overloading
• Runtime Polymorphism using virtual
functions
Message Passing obj1.sendMessage(obj2);
• Objects communicate with one
another using messages (function
calls).
• Promotes interaction between
objects.

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)

1.3 Data types, Type compatibility, Declaration of variable, Dynamic initialization of


variable, Reference variable, Type casting

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

Derived Data array, pointer,


Data types derived from basic types.
2 Types reference, function

User Defined Custom data types created by the class, struct, union,
3 Data Types programmer according to their need. typedef, using

1. Character Data Type (char)


The character data type is used to store a single character. The keyword used to define a
character is char. Its size is 1 byte, and it stores characters enclosed in single quotes (' '). It can
generally store upto 256 characters according to their ASCII codes.
Example:
#include <iostream>
using namespace std;

int main() {

// Character variable
char c = 'A';
cout << c;

return 0;
}

Output
A

2. Integer Data Type (int)


Integer data type denotes that the given variable can store the integer numbers. The keyword
used to define integers is int. Its size is 4-bytes (for 64-bit) systems and can store numbers
for binary, octal, decimal and hexadecimal base systems in the range from -2,147,483,648 to
2,147,483,647.
Example:
#include <iostream>
using namespace std;
int main()
{
// Creating an integer variable
int x = 25;

7
cout << x << endl;
// Using hexadecimal base value
x = 0x15;
cout << x;
return 0;
}

Output
25
21

3. Boolean Data Type (bool)


The boolean data type is used to store logical values: true(1) or false(0). The keyword used
to define a boolean variable is bool. Its size is 1 byte.
Example:
#include <iostream>
using namespace std;

int main() {

// Creating a boolean variable


bool isTrue = true;
cout << isTrue;
return 0;
}

Output
1

4. Floating Point Data Type (float)


Floating-point data type is used to store numbers with decimal points. The keyword used to
define floating-point numbers is float. Its size is 4 bytes (on 64-bit systems) and can store
values in the range from 1.2E-38 to 3.4e+38.
Example:
#include <iostream>
using namespace std;

int main() {

// Floating point variable with a decimal value


float f = 36.5;
cout << f;

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() {

// double precision floating point variable


double pi = 3.1415926535;
cout << pi;

return 0;
}

Output
3.14159

6. Void Data Type (void)


The void data type represents the absence of value. We cannot create a variable of void type.
It is used for pointer and functions that do not return any value using the keyword void.

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;

cout << "num_int = " << num_int << endl;


cout << "num_double = " << num_double << endl;

return 0;
9
}

Output:
num_int = 9
num_double = 9.99

Data Loss During Conversion (Narrowing Conversion)


As we have seen from the above example, conversion from one data type to another is prone
to data loss. This happens when data of a larger type is converted to data of a smaller type.

Explicit Type Conversion:


When a programmer manually changes data from one type to another, this is known
as explicit conversion. This type of conversion is also known as type casting.
Syntax: (data_type)expression;
Example:
#include <iostream>

using namespace std;

int main() {
// initializing a double variable
double a= 3.56;
cout << "value of a which is in double = " << a << endl;

// C-style conversion from double to int


int b = (int)a;
cout << "value of b which is in int = " << b << endl;

// function-style conversion from double to int


int c = int(a);
cout << "c = " << c << endl;

return 0;
}

Output:
value of a which is in double = 3.56
value of b which is in int = 3
c =3

Different Ways to Initialize a Variable in C++


Variables are arbitrary names given to the memory location in the system. These memory
locations are addressed in the memory. In simple terms, the user-provided names for memory
locations are called variables. Additionally, a data type is used to declare and initialize a
variable.
Variables once declared, are assigned some value. This assignment of value to these variables
is called the initialization of variables.
Example:
#include <iostream>
10
using namespace std;
int main()
{
// initialization
int var1 = 5;
int var2(23);
int var3{ 34 };
auto var4 =45;

// 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:

Dynamic initialization of variable


Dynamic initialization of object refers to initializing the objects at run time i.e., the initial
value of an object is to be provided during runtime.
Dynamic initialization of objects is useful because:
• It utilizes memory efficiently.
• Various initialization formats can be provided using overloaded constructors.
• It has the flexibility of using different formats of data at run time considering the
situation.
Example:
#include <iostream>
using namespace std;

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;

cout << "Enter radius of circle: ";


cin >> r; // value given at runtime

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

Memory Management Operators: new and delete


Used for dynamic memory allocation and deallocation.
• new allocates memory at runtime
• delete frees the memory
new Operator
The new operator requests for the allocation of the block of memory of the given size of
type on the Free Store (name for the part of heap memory available for new operator). If
sufficient memory is available, a new operator initializes the memory to the default value
according to its type and returns the address to this newly allocated memory.
Syntax: new data_type;
Example: int *nptr = new int;
We allocated the memory for a single integer using new and stored its address in the integer
pointer nptr. We can also initialize the allocated memory by providing an initial value:
int *nptr = new int(10);

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

Allocate Block of Memory (Array)


A new operator is also used to dynamically allocate a block (an array) of memory of given
data type as shown below:
new data_type[n];
This statement dynamically allocates memory for n elements of given data_type. Arrays can
also be initialized during allocation.
#include <bits/stdc++.h>
using namespace std;

int main() {

// Declared a pointer to store


// the address of the allocated memory
int *nptr;

// Allocate and initialize array of


// integer with 5 elements
nptr = new int[5]{1, 2, 3, 4, 5};

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

Manipulators: endl, setw, setprecision, etc.


Used to format output.
endl — End Line Manipulator
Purpose:
• Moves the cursor to the next line, like \n.
• Also flushes the output buffer (i.e., forces output to be printed immediately).
setw(n) — Set Width
Purpose:
• Sets the minimum width of the next output field.
• Adds leading spaces if the content is shorter than the width.
• Comes from the <iomanip> header.
setprecision(n) — Set Decimal Precision
Purpose:
• Controls the number of digits displayed for floating-point values.
• When used with fixed, it sets the number of digits after the decimal.
Example:
#include <iostream>
#include <iomanip> // required for manipulators like setw, setprecision
using namespace std;
int main() {
int a = 10, b = 200;
float c=45.12454;
cout << "Without setw:" << endl;
cout << a << endl << b << endl;
cout << "With setw:" << endl;
cout << setw(5) << a << endl;
cout << setw(5) << b << endl;
cout<<setprecision(4) <<c;
return 0;
}
Output:

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

The basic requirement for writing this


program is to have knowledge of loops

To find the factorial of number


iterate over range from number to one
*/

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;

// Global Declaration Section


INTEGER num = 0, fact = 1, storeFactorial = 0;

// Function Section
INTEGER factorial(INTEGER num)
{
// Iterate over the loop from
// num to one
for (INTEGER i = 1; i <= num; i++) {
fact *= i;
}

// Return the factorial


return fact;
}

// Main Function
INTEGER main()
{
// Given number Num
INTEGER Num = 5;

// Function Call
storeFactorial = factorial(Num);
cout << msg;

// Print the factorial


cout << Num << "! = "
<< storeFactorial << endl;

return 0;
}
Output:

Displaying output using Insertion Operator ( << )


• << is called Insertion or PutTo operator .
• It is similar to printf () in c programming.

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

Extraction Operator ( >> )


• >> is called Extraction or Getfrom operator.
• It is similar to scanf() in c programming.
• It extracts the value from the keyboard and assigns it to the variable on its R.H.S.
Syntax: cin << variable-name;
Example: cin >> num1 ;
The above statement causes the program to wait until the user type a number. The types
number is then places in a variable num1.
• The identifier cin is a predefined object that represents the standard input stream.
• Here the standard input stream is keyboard.

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

Generally class specification has two parts:


1) class declaration
2) class function definitions.

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

Access Modifiers in C++


In C++, access modifiers or access specifiers in a class are used to assign the accessibility to
the class members, i.e., they set some restrictions on the class members so that they can't be
directly accessed by the outside functions. Access modifiers are used to implement an
important aspect of Object-Oriented Programming known as Data Hiding.
There are 3 types of access modifiers available in C++:
1. Public
2. Private (default)
3. Protected
Let us now look at each one of these access modifiers in detail.
1. Public Specifier
All the class members declared under the public specifier will be available to everyone. The
data members and member functions declared as public can be accessed by other classes and
functions too. The public members of a class can be accessed from anywhere in the program
using the direct member access operator (.) with the object of that class.
Example:
#include<iostream>
using namespace std;

// Class definition
class Circle {
public:
double radius;
double compute_area() {
return 3.14*radius*radius;
}
20
};

int main() {
Circle obj;

// Accessing public members 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.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() {

// member function can access private


// data member radius
return 3.14*radius*radius;
}

};

int main() {
Circle obj;

// trying to access private data member


// directly outside the class
21
obj.radius = 1.5;
cout << "Area is:" << obj.compute_area();

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:

// Returns the private variable (getter)


double getRadius()
{
return radius;
}

// Set the private variable (setter)


void setRadius(double val)
{
radius = val;
22
}

double compute_area() {
return 3.14*radius*radius;
}

};

int main() {
Circle obj;

// Accessing private variables using public getter and setter methods


obj.setRadius(1.5);
cout << "Radius is: " << obj.getRadius() << endl;
cout << "Area is: " << obj.compute_area();

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;

};

// Derived class from public base class


class Child : public Parent {
public:
void setId(int id) {

// Child class is able to access inherited


// protected data members of base class
id_protected = id;
}

int getId() {
23
return id_protected;
}
};

int main() {
Child obj1;

obj1.setId(81);
cout << "ID: " << obj1.getId();
return 0;
}
Output
ID: 81

Defining member functions:


• The functions, which are declared inside the class, are called member functions of that
class.
• Only member functions can access the private members of the class.
• Generally member functions are placed in a public section. But they can be placed in a
private section also.
• Member function can be defined in two places.
1) Outside the class definition
2) Inside the class definition

1)Defining member function out-side the class definition:


• In this, the member functions that are declared inside the class have to be defined out side
the class.
• The member function incorporates a’ membership identity label’ in the header. This label
tells the compiler which class the function belongs to.
• The general syntax of defining any member function outside the class is as follows:
Return- data-Type class-name :: function-name (argument –declaration)
{
function Body
}

The membership label ‘class-name:: ‘ tells the compiler that the function belongs to the
spiffed class.
• The symbol :: is called scope resolution operator.
Example:

// C++ program for Outside the Class Definition


#include <iostream>
using namespace std;
class rectangle {
private:
int length;
int breadth;

24
public:
// Constructor
void getdata(int l, int b)
{
length = l;
breadth = b;
}

// area() function defined outside the class


int area();

// perimeter() function defined outside the class


int perimeter();
};

// function defining using scope resolution operator "::"


int rectangle::area()
{
return (length * breadth);
}

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

You might also like