Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

5-Features of OOP, Differences between structured and object-oriented Progra

The document provides an overview of Object-Oriented Programming (OOP), detailing its fundamental concepts such as classes, objects, data abstraction, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. It highlights the differences between C and C++, emphasizing the advantages of C++ as an object-oriented language with features like exception handling and namespaces. Additionally, the document includes examples and syntax for defining classes and member functions in C++.

Uploaded by

khushibarbie04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

5-Features of OOP, Differences between structured and object-oriented Progra

The document provides an overview of Object-Oriented Programming (OOP), detailing its fundamental concepts such as classes, objects, data abstraction, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. It highlights the differences between C and C++, emphasizing the advantages of C++ as an object-oriented language with features like exception handling and namespaces. Additionally, the document includes examples and syntax for defining classes and member functions in C++.

Uploaded by

khushibarbie04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

BCSE102L

Structured and Object Oriented Programming

Module 5 – Overview of Object Oriented


Programming
Dr. C.R.Dhivyaa
Assistant Professor
School of Computer Science and Engineering
Vellore Institute of Technology, Vellore
Module 5
Object Oriented Programming
• Object-oriented programming (OOP) is a programming paradigm based on
the concept of objects, which can contain data and code
• OOP allows decomposition of problem into a number of entities called
objects and then builds data and functions around these objects.
• View the problem world as a set of objects and communication between the
objects.
• Entire world around as can be thought as a set of objects.
• Objects have characteristics and they can perform some functions
3
Object Oriented Programming
Organization of data and functions
in OOP
• Different things to different people.
• Data of an object can be accessed
only by the functions associated with
that object.
• Functions of one object can access
the functions of other objects.

4
Limitations in C
• No Object-Oriented Programming (OOP)
• Manual Memory Management
• No Exception Handling
• Limited Standard Library
• Lack of Modern Features
• Complex Debugging
• Platform Dependence

5
Basic Concepts of OOP
Concepts extensively used in Object-Oriented Programming.
1. Classes
2. Objects
3. Data Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic Binding
8. Message Passing

6
Basic Concepts of OOP
1.Class
• A class in C++ is a user-defined type or data structure declared with a keyword
class that has data and functions as its members.
• A class can be used by declaring an object.
• Classes act as a user-defined data type to create objects with similar properties.
• A Class is merely a blueprint of data.
• When a class is created no memory is allocated but when an instance is created by
declaring an object, memory is then allocated to store data and perform required
functions on them.

7
Basic Concepts of OOP
Defining Class in C++
• A Class is defined by a keyword class followed by a class name (user's choice) and a
block of curly brackets with semicolons after the block.T
• The block starts with access specifiers followed by data members and member
functions.
• Access Specifiers - defines how the members of the class can be accessed.
• Public: members can be accessed outside the class.
• Private: members cannot be accessed outside the class.
• Protected: members cannot be accessed(viewed) from outside the class, but can be
accessed in inherited classes(subclasses).
8
Basic Concepts of OOP
Class- Syntax and Example

9
Basic Concepts of OOP
2.Object
• Objects are basic run-time entities in an object oriented system.
• Note: When a class is defined only the blueprint of data structure is defined as no
memory is allocated.
• To use data and its member function we can declare objects. We can declare objects
by mentioning the class
• followed by the user-defined object name.
• Simply it is called as instance of class
• Syntax: ClassName ObjectName;
• Example:
• fruit mango; - will create an object mango belonging to the class fruit.10
Basic Concepts of OOP
Classes and Objects in Railway Reservation System
Class Objects

Train InterCity Express


Coaches/Compartment S1
Station Katpadi

Passenger Any Person Travelling in Train


Employees of Railways TTR
Ticket Ticket possessed by a passenger

11
Basic Concepts of OOP
3.Data Abstraction
• Providing only essential information to the outside world and hiding their
background details.
• In other words, avoiding unnecessary and irrelevant information and only
showing the specific details of what users want to see
• By abstraction, a programmer hides all but the relevant data about an object in order
to reduce complexity and increase efficiency.
• In C++, classes uses the concept of data abstraction, they are called as “ Abstract
Data Types”(ADT)- we use abstract classes and interfaces to achieve this
property.

12
Basic Concepts of OOP
Data Abstraction in Railway Reservation System

Class Information Hidden

Train Engine Manufacturing date

Coaches/Compartment Cleanliness, Color

Station Length, Shops

Passenger Number of children

Employees of Railways Employee id, Salary

13
Basic Concepts of OOP
4. Encapsulation
• Encapsulation means encapsulating (binding or wrapping)code and data
together into a single unit.
• Data is not accessible to the outside world, and only those functions which are
wrapped inside the class can access it.
• It provides interface between the object’s data and the program.

14
Basic Concepts of OOP
5. Inheritance
• Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It helps to reduce the code.
• Reusability- we can add additional features to an existing class without modifying it.

• Base Class : It is the class whose properties are inherited by another class. It is also
called as super class or Parent Class.
• Derived Class : It is a class that inherits properties from base class. It is also called as
sub class or Child Class 15
Basic Concepts of OOP
6. Polymorphism
• Ability to take more than one form, An operation may exhibit different behavior in
different instances.
• Behavior depends on the type of the data being used in the operation.
• Polymorphism allows the same function to behave differently in different classes.

16
Basic Concepts of OOP
7. Dynamic Binding
• Dynamic Binding, also known as Late Binding, is a concept in Run-time
Polymorphism where function calls are determined at runtime instead of compile time.
• Binding refers to linking of a procedure call to the code to be executed in response
to the call.
• Associated with polymorphism and Inheritance.
• For example: The procedure “ draw” in the previous slide, every object will
have this method/procedure.
• Its algorithm is unique with respect to each object and it will be redefined in each class
that defines the object.
• At runtime, the code matching the object under current reference will be called. 17
Basic Concepts of OOP
8. Message Passing
• An Object-Oriented Program consists of set of objects that communicate with
each other.
• The process involves
• Create class that define objects and their behavior.
• Create Objects from class definition and
• Establish communication among objects
• A message for an object is a request for execution of a procedure – will invoke a
function(procedure)in the receiving object that generates the desired result.

18
Basic Concepts of OOP
8. Message Passing

19
Features of OOP
• Emphasis is on data rather than procedure.
• Programs are divided into what is known as objects.
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are tied together in the data
structure.
• Data is hidden and cannot be accessed by the external functions.
• Objects may communicate with each other through functions.
• New data and functions may easily be added whenever necessary.
• Bottom-up approach is followed in program design.

20
Difference Between C and C++
C C++
C is a structural or procedural C++ is an object-oriented
oriented programming language. Does programming language, so it is safer
not support classes and objects. and well-structured programming
language than C.
Supports classes and Objects
C follows the top-down approach C++ follows the bottom-up approach

Data can be easily manipulated by the C++ - Secure Language- Supports


outsiders Encapsulation and Data Hiding

Does not support the function C++ supports the function overloading.
overloading
Does not support the function C++ supports the function overriding.
overriding.
32 Keywords 52 Keywords
21
Difference Between C and C++
C C++

Exception Handling- C does not provide C++ provides direct support to exception
direct support to the exception handling handling by using a try-catch block

scanf and printf functions are used for input cin and cout are used for input and output
and output operations operations

C supports calloc() and malloc() functions for C++ supports a new operator for the
the memory allocation, and free() function memory allocation and delete operator for
for the memory de-allocation the memory de-allocation.

C language does not support the inheritance C++ supports the inheritance.

C program uses <stdio.h> header file C++ program uses <iostream.h> header
file.
22
Namespaces in C++
• Consider a situation, when we have two persons with the same name, “x”, in the
same class.
• What we do to differentiate them??
• Same situation in C++ applications too--- writing some code that has a function
called xyz() and there is another library available which is also having same
function xyz().
• A namespace is designed to overcome this difficulty and is used as additional
information to differentiate similar functions, classes, variables etc. with
the same name available in different libraries. Using namespace, you can
define the context in which names are defined.( Simply it defines the Scope) 23
Example C++ Program

24
Commonly used Header files

25
Commonly used Header files

26
C++ Keywords

27
Classes and Objects
• A class in C++ is a user-defined type or data structure declared with a
keyword class that has data and functions as its members.
• A class can be used by declaring an object.
• Classes act as a user-defined data type to create objects with similar properties.
• A Class is merely a blueprint of data.
• When a class is created no memory is allocated but when an instance is created
by declaring an object, memory is then allocated to store data and perform
required functions on them.

28
Classes
• A Class is defined by a keyword class followed by a class name (user's choice) and
a block of curly brackets with semicolons after the block.T
• The block starts with access specifiers followed by data members and member
functions.
• Access Specifiers - defines how the members of the class can be accessed.
• Public: members can be accessed outside the class.
• Private: members cannot be accessed outside the class.
• Protected: members cannot be accessed(viewed) from outside the class, but can
be accessed in inherited classes(subclasses).

29
General Form of Class
A Class is a way to bind the data and its associated functions together.

class class name


{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};

30
How data is hided in class?

31
Class - Example
• Contains two data members and two function
members.

class product • Data members are private by default


{ • Function members are public by declaration
int number;
float cost; • Getdata() – used to assign values to member
public: variables
void getdata(int a, float b);
void putdata(); • Putdata()- displaying the values
}; • Note: Data members cannot be accessed by any
function that is not a member of class “ product”
• Data members are usually declared as private
• Member functions are declared public. 32
Creating Objects
• Note: Declaration of “ product” – does not define any objects but only specifies
what they contain.
• Once class created/declared- we can create variables of that type by using the class
name

33
How to access class members?

34
Defining member functions

Member functions of a class are used to access, use or modify the data
members of that class. We can define member functions in two ways:
Outside the class definition
Inside the class definition

35
Defining member functions
#include <iostream>
Inside the class definition using namespace std;
class product
{
We can define a member int number;
float cost;
function inside the class public:
void getdata()
directly without declaring {
cout<<"enter product details";
it first in class. cin>>number>>cost;
}
void putdata()
{
cout<<"number="<<number;
cout<<"\ncost="<<cost;
}
};
int main()
{
product p1; // object creation
p1.getdata();
p1.putdata(); 36
}
Defining member functions
Outside the class definition
To Define a member function outside the class we need to declare it first inside the class
and then define it outside the class according to the following syntax:

ReturnType classname::memberfunction(arguements)
{
Function body
}

:: ->Scope resolution operator


Scope of the function is restricted to the class name specified in the header.
37
Defining member functions
Outside the class definition
#include <iostream> int main()
using namespace std; {
class product
product p1;
{
int number;
p1.getdata();
float cost; p1.putdata();
public: }
void getdata()
{
cout<<"enter product details";
cin>>number>>cost;
}
void putdata();
};

void product::putdata()
{
cout<<"number="<<number;
cout<<"\ncost="<<cost;
38
}
Nesting of member functions
void s:: input()
#include<iostream> {
using namespace std; cin>>m>>n;
class s }
{
int m,n; void s::display()
public: {
void input(void); cout<<"Largest value="<<largest()<< "\n";
void display(void); }
int largest(void);
}; int main()
int s:: largest() {
{ s A;
if(m>n) A.input();
return m; A.display();
else return 0;
return n; }
}
39
Private Member Function
include<iostream>
void sample :: update(void)
using namespace std;
class sample {
{ read(); // no object is used
int number; cout<<"number="<<number;
void read() }
{ int main()
cout<<"enter no"; {
cin>>number; sample s1;
}
s1.update();
public:
void update(); return 0;
}; }

• Private member function can only be called by another function that is a member of its
class
• Even an object cannot invoke a private function
• S1.read() // Illegal- objects cannot access private members
• read() can be called by the function update() to update the value of number
40
Arrays within a class
Arrays can be used as member variables in a class.

class product
{
int number[10]; // type of integer array
public:
void getdata(void);
void putdata();
};

41
How memory is allocated for objects??

42
This pointer
• Every object in C++ has access to its own address through an important pointer
called this pointer.
• this pointer is an implicit parameter to all member functions.
• Therefore, inside a member function, this may be used to refer to the invoking
object.
• Only member functions have this pointer.
• this pointer is used to access the current object addresses
• this pointer is used to distinguish the data members from the local variable when
both are declared with the same name.
• So, to identify the data members, we use this pointer.

43
Example: To find the object address and
Differentiate data members from local variables
#include<iostream>
int main()
using namespace std;
{
class test
test t; // created an object
{
t.show();
int a,b;
public: t.display(10,20);
void show() return 0;
{ }
cout<< "obj address = "<< this; // give current obj address
}
void display(int a,int b)
{
this->a=a;
this->b=b;
cout<<"\nvalues of a and b"<<this->a<<this->b; // can also be written as (*this).b=b
44
}
Why Constructor?? Constructor
• In implementation of class, member functions are used to provide initial values to
private member variables.
• For Example:
• X.getdata(100,75.45); passes initial values as arguments to the function
getdata()
• This values are assigned to private variables of object x.
• All these function call statements are used with appropriate objects that already
created.
• Observation??
• These functions cannot be used to initialize the member variables at the
time of creation of their objects. 45
Constructor
Main philosophy of C++?
• Creating any user defined data type such as class – behave like similar to basic built
in data types.
• We can able to initialize a class type variable(object) when it is declared
as like same initialization of ordinary variable.
• For example:
• int x=10;
• float y=22.14;

• C++ provides a special member function called constructor which enables an


object to initialize itself when it is created.
• Automatic initialization of objects.
46
Constructor
• It is a special member function having same name as it’s class.
• It is used to initialize the objects of that class type with a legal initial
value.
• Constructor is automatically called/invoked when object is created.
• They should be declared in the public section.
• They do not have any return type.
• It is called as “ Constructor” because it constructs the value of data
members of the class.

47
Constructor
• It is a special member function having same name as it’s class.
• It is used to initialize the objects of that class type with a legal initial
value.
• Constructor is automatically called/invoked when object is created.
• They should be declared in the public section.
• They do not have any return type.
• It is called as “ Constructor” because it constructs the value of data
members of the class.

48
Types of Constructors
Four types of constructors in C++:

1. Default Constructors

2. Parameterized Constructors

3. Copy Constructors

4. Dynamic Constructors

49
Default Constructors
• A constructor which does not receive any parameters is called a Default

Constructor or a Zero Argument Constructor.

• Every class object is initialized with the same set of values in the default

constructor.

• Even if a constructor is not defined explicitly, the compiler will provide a

default constructor implicitly.

50
#include <iostream>
Default Constructors
using namespace std;
class employee
{
public:
int age;
employee() // default constructor
{
age=50;
}
};
int main()
{
employee e1;
cout<<e1.age;
return 0;
} 51
Parameterized Constructor
• Using the default constructor, it is impossible to initialize different

objects with different initial values.

• A Parameterized Constructor is a constructor that can accept one or

more arguments.

• This helps programmers assign varied initial values to an object at the

creation time.

52
#include <iostream> Parameterized Constructor
using namespace std;
class employee
{
public:
int age;
employee(int x) // Parameterized constructor
{
age=x;
}
};
int main()
{
employee e1(50);
employee e2(40);
cout<<e1.age;
cout<<"\n"<<e2.age;
return 0;
53
}
Parameterized Constructor
Passing initial values as arguments to the constructor function when an object is
declared.
Can be done in two ways:
Calling Constructor Explicitly
Calling Constructor implicitly
Explicit call
integer x = integer(10,100); // creates an object x and passes value 10 and 100 .
Implicit call
integer x(10,100);

54
#include <iostream>
using namespace std;
Parameterized Constructor
class employee
{
public:
int age;
employee(int x); // parametrized Constructor declared
};
employee::employee(int x)
{
age=x;
}
int main()
{
employee e1(50); // Implicit Call
employee e2= employee(40); // Explicit Call
cout<<e1.age;
cout<<"\n"<<e2.age;
return 0;
55
}
Copy Constructor

• A Copy constructor in C++ is a type of constructor used to create a


copy of an already existing object of a class type.
• A copy constructor comes into the picture whenever there is a need
for an object with the same values for data members as an already
existing object. A copy constructor is invoked when an existing object is
passed as a parameter.
• integer I2=I1;

56
#include <iostream>
using namespace std;
Copy Constructor
class employee
{
public:
int age;
employee(int x)
{
age=x;
}
employee(employee &emp) // Copy constructor
{
age=emp.age;
}};
int main()
{
employee e1(50);
employee e2= e1; // // Copy constructor
cout<<e1.age;
cout<<"\n"<<e2.age;
return 0; 57
}
Dynamic Constructor

• While creating objects, When the allocation of memory is done

dynamically using a dynamic memory allocator “new” in a constructor,

it is known as a Dynamic constructor.

• By using this, we can dynamically initialize the objects i.e memory is

allocated at run time.

58
Destructor

• As name implies, it is used to destroy the objects that have been created by a
constructor.
• A Destructor is also a member function that is instantaneously called whenever an
object is destroyed. The destructor is called automatically by the compiler when the
object goes out of scope, i.e., When a function ends, the local objects created within
it are also destroyed.
• The destructor has the same name as the class name, but the name is preceded by a
tilde(~).A destructor has no return type and receives no parameters.
• ~ integer() { }

59
#include <iostream>
using namespace std;
Example
class A int main()
{
{
int *value;
public: A obj1;
A() //Default constructor
cout<<"The value of object obj1 is: ";
{
value = new int; //Memory allocation at run time obj1.display();
*value = 1234;
return 0;
}
void display() }
{
cout<< *value <<endl;
}
~A()
{
cout<<"deleted";
}
};
60
Static Data Members
• Static data members are declared by using the static keyword inside the class, but as they have the
lifeline until the program runs and is accessible to every class object they must have to initialize
outside the class.
• To initialize static data members, we use the scope resolution operator to access them and initialize
after the class declaration and before the main function.
• As the memory block of static data members is shared by every object of the class. So, if there
is any change made in the static data member then it will be updated for every other object of
the class.
• Static data members can be accessed anywhere in the program after the declaration of class either
using the class instance or using scope resolution, class name, and variable name. There is no need
to create objects to access them.
• datatype class_name:: variable name=value
61
#include <iostream>
Static Data Members
using namespace std; int room::roomscount=0; // static data member
class room
{ int main()
public: {
static int roomscount;
int length; room r1(10,20);
int breadth; room r2(20,30);
room(int l, int b)
{ room r3(15,20);
length =l; cout<<r3.area();
breadth=b;
roomscount++; cout<<"count="<<room::roomscount;
} }
int area()
{
return length*breadth;
}
};
62
Static Members functions
• Static members functions are defined by using the static keyword. As we have defined these functions as
static, they have class properties rather than object properties.
• They can be called even if no object of class be created.
• So we can access static member functions by using the class name and scope resolution operator.
• A static member function can only access static data members and other static member functions from outside
the class.
• A static member function is independent of any object of the class.
• A static member function can be called even if no objects of the class exist.
• A static member function can also be accessed using the class name through the scope resolution operator.
• A static member function can access static data members and static member functions inside or outside of the
class.
• Static member functions have a scope inside the class and cannot access the current object pointer.
• You can also use a static member function to determine how many objects of the class have been created.
• class_name:: function_name()
63
#include <iostream>
using namespace std;
Static Members functions
class room
{ int room::roomscount=0; // static member initialization
public:
static int roomscount;// static member declaration int main()
int length; {
int breadth;
room r1(10,20);
room(int l, int b) room r2(20,30);
{
length =l; room r3(15,20);
breadth=b; cout<<r3.area();
roomscount++;
} room::getRoomCount();
int area() }
{
return length*breadth;
}
static void getRoomCount() // static member function definition
{
cout<<"count="<<roomscount;
}
64
};
Parameter Passing to Functions
The parameters passed to function are called actual parameters.
The parameters received by function are called formal parameters.
• Pass/Call by Value: In this parameter passing method, values of actual parameters are copied
to function’s formal parameters and the two types of parameters are stored in different
memory locations. So any changes made inside functions are not reflected in actual parameters
of caller.
• Pass/Call by Reference: Both actual and formal parameters refer to same locations, so any
changes made inside the function are actually reflected in actual parameters of caller.(Definition
based on Pointers).
Passing arguments to a function copies the reference of an argument into the formal parameter.
Inside the function, the reference is used to access the actual argument used in the call. (Definition
based on Reference variable – in C++) 65
Pass/Call by Value – C++ program
#include <iostream>
using namespace std;
void swap(int x, int y);
int main ()
{
int a = 100; int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
swap(a, b); // calling a function to swap the values.
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
void swap(int x, int y)
{
int temp=x;
x=y;
y=temp;
}
66
Pass/Call by Address- C++ Program
#include <iostream>
using namespace std;
void swap(int *x, int *y);
int main ()
{
int a = 100, b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
swap(&a, &b);
cout << "After swap, value of a :" << a << endl; //Value of a printed
cout << "After swap, value of b :" << b << endl;// Value of b printed
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
67
Pass/Call by Reference- C++ Program
#include <iostream>
using namespace std;
void swap(int &x, int &y);
int main ()
{
int a = 100, b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
swap(a, b);
cout << "After swap, value of a :" << a << endl; //Value of a printed
cout << "After swap, value of b :" << b << endl;// Value of b printed
return 0;
}
void swap(int &x, int &y) // x and y are called reference variables
{
int temp= x;
x = y;
y = temp;
}
68
Inline Functions
• Main objective of functions in a program is to save memory.

• Every time when function is called it takes lot of time to execute series of instructions

for tasks(For ex: jumping to function, saving registers, push arguments and return to

the calling function).

• C++ - To eliminate the cost of calls to small functions- it proposes inline

function.(Similar to Macros)

• Termed as macros expansion.

69
Inline Functions

70
Inline Functions
• Inline function is a function that is expanded in line when it is called. When the inline

function is called whole code of the inline function gets inserted or substituted at the

point of inline function call.

• It is a method to optimize the code and enhance a program’s performance.

• It improves the execution time and speed of the program.

• SYNTAX inline return-type function-name(parameters)


{
// function code
}
71
Inline Functions
#include <iostream>
using namespace std;
inline int max(int x,int y)
{
return x>y ? x :y;
}
int main( )
{
int n1,n2;
cout<<"Enter two numbers \n";
cin>>n1>>n2;
int m=max(n1,n2);
cout<<"Max="<<m<<endl;
return 0;
} 72
Some points in Inline Functions
• Inline function executes faster than normal function.
• Inline function does not work as inline when code contains loops, recursions,
goto, switch, static variable etc.
• inlining - is only a request to the compiler, not a command. The compiler can
ignore the request for inlining.
• static variables
• Recursive call (Recursive functions)
• that contain switch or go-to statements
• that contain while, do-while, or for looping controls
• with a variable number of arguments (Var_Args)
• function definition is too big or complicated 73
Functions with Default arguments
In C ++ is it possible for a function not to specify all its arguments??
YES
• Some of the arguments may be specified their default values at the time of declaring the
function.
• When a function having default argument is called, compiler checks for the number and
type of argument as well as was not specified during the function call, default value of that
argument is assumed.
For Example:
void show (int x, int y = 20); // two argument of int type out of which second
argument is default.
1. show(10) – x is assigned 10 and y is assigned 20 as default
2. show(10,100) – x is assigned 10 and y is assigned 100 because 20 is overridden. 74
Points to remember when using default
arguments
In a function with default argument, if one argument is default, all successive arguments
must be default.
We cannot provide default values in the middle of the arguments or towards left side.
Examples:
void show (int x, int y = 20, int z=35); // legal
void show (int x, int y = 30, int z); // Illegal
void show (int x=20, int y); // Illegal
void show (int x=10, int y = 20, int z=35); // legal

75
Functions with Default arguments
#include <iostream>
using namespace std;
int main( )
{
void show(char* s="Good Morning"); // default argument
show();
show("Good Evening");
return 0;
}
void show(char *s)
{
cout<<"Argument to show :"<<s<<endl;
} 76
Functions
#include <iostream>
with Default arguments
using namespace std;
void show(int a, int b=20 ); // default argument
int main( )
{
show(10);
show(10,30);
return 0;
}
void show(int x, int y)
{
cout<<"add="<<x+y;
77
}
Functions with Objects as arguments
In C++, Similar to returning and passing arguments to function of basic type like int,

char, double, float, char* etc.

we can pass objects of class to functions and even return objects from

functions(Passing and returning object)

demo show(demo);

// For a function show which takes an object of demo class type and return an object

of demo class.

78
Example- passing objects to function
#include <iostream>
using namespace std; int main()
class demo {
{ demo d1,d2;
int num; d1.input(20);
public : d2.copy(d1); // passing object to function
void input(int x) cout<<"Object d1"<<endl;
{
d1.show( );
num=x;
} cout<<"Object d2"<<endl;
void copy(demo d) d2.show( ); return 0;
{ }
num=d.num;
}
void show( )
{
cout<<"num="<<num<<endl;
}
};
79
Example- Returning objects as arguments
#include <iostream> int main( )
using namespace std; {
class demo
demo d1, d2;
{
int num;
d1.input(20);
public : d2=d1.copy( ); //returned object is assigned to d2
void input(int x) cout<<"Object d1\n";
{ d1.show( );
num = x; cout<<"Object d2\n";
} d2.show( );
demo copy( )
return 0;
{
demo temp; }
temp.num = num;
return temp; // returning objects
}
void show( )
{
cout<<"num="<<num<<endl;
80
}};
Friend Functions & Classes
• Note: Private members cannot be accessed from outside the class. i.e a
non-member function cannot have an access to private data of a class.
• If any situation where we would like two or more classes to
share a particular function, what to do??
• C++ allows a common function to be made friendly with both
the classes, thereby allowing the function to have access to the
private data of these classes.
• Such a function need not be a member of any other classes.

81
Friend Functions- Declaration

• To make an outside function friendly to a class, we have to declare this function as


friend of the class.
• Function is defined anywhere like normal C++ function.
• Function definition does not use either keyword friend or scope operator::
• Although not a member function, has full access rights to private
member of the class.

82
Characteristics of Friend Functions
• A friend function is created by placing the keyword friend in the function declaration
but not in function definition. Exception is if you declare and define at the same place.
• A friend function is a friend of the class in which it is declared.
• A friend function is not a member function of the class and cannot be called from any
object of the class using dot operator.
• A friend function can have full access to the public, private and protected data member
of the class to which it is a friend.
• The arguments of friend functions are usually objects of the class to which it
is a friend.
• A friend function not being a member function of class is called as a normal function.
83
Characteristics of Friend Functions
• A friend function can be friend of more than one class.

• A function of one class can be a friend of another class.

• We can have whole class as a friend of another class

• We use friend function usually with multiple classes but can used with single class also.

• A friend function can be declared in the public or private visibility mode without

affecting its meaning.

84
class demo Syntax- Friend Functions
{
data members :
public :
members functions;
// friend function declaration
friend data_type function_name (parameters);

};
data_type function_name (parameters) //definition
{
function definition;
} 85
Example -1
#include <iostream>
int main( )
using namespace std;
{
class demo
demo F;
{
F.input(30);
int y;
cout<<"Square is="<<findsqr(F);
public :
return 0;
void input(int x)
}
{
y=x;
}
friend int findsqr(demo d);
};
int findsqr(demo d)
{
return d.y * d.y;
}

86
#include <iostream> Example -2
using namespace std;
class sample int main( )
{ {
int a,b; sample x;
public : x.setvalue();
void setvalue() cout<<"Average is ="<<avg(x);
{ return 0;
a=10; }
b=20;
}
friend float avg(sample s);
};
float avg(sample s)
{
return float(s.a+s.b)/2;
} 87
Example-3 Max of two data of two different classes
#include <iostream> Friend function with two different class
using namespace std; void findmax(first A, second B)
class second; //forward declaration {
class first if(A.fx>B.sx)
{ cout<<"first class is greater";
int fx; else
public : cout<<"second class is greater";
void inputf(int x) }
{ fx=x; int main( )
} {
friend void findmax(first A, second B); first F;
}; second S;
class second F.inputf(40);
{ S.inputs(70);
int sx; findmax(F,S);
public : return 0;
void inputs(int x) }
{
sx = x;
}
friend void findmax(first A, second B);}; 88
Example-4: Function of one class- friend of another class
#include <iostream>
using namespace std; void sam::disp(sample s)
class sample; // forward declaration {
class sam cout << s.a << " " << s.b;
{ }
public:
void disp(sample s); int main()
}; {
sample s1;
class sample sam s;
{ s.disp(s1);
int a; return 0;
public: }
int b;
sample()
{
a = 10;
b = 20;
}
friend void sam::disp(sample s);
}; 89
Friend Class
A friend class in C++ is a class that is granted special access to the private and protected members of
another class. It is declared using the friend keyword inside the class whose private members need to be
accessed.
✅ Access to Private and Protected Members: A friend class can access both private and protected
members of the class that declares it as a friend.
✅ Declared Inside Another Class: The friendship is established by writing friend class ClassName; inside
the class whose private members should be accessible.
✅ One-Way Friendship: If class A declares class B as a friend, B can access private members of A, but A
cannot access private members of B unless B also declares A as a friend.

90
Example-5: Whole class as a friend of another class

#include <iostream>
int main() {
using namespace std;
A a;
B b;
class B; // Forward declaration
b.show(a); // B is allowed to access private data of A
return 0;
class A {
}
private:
int data = 10; // Private member
public:
friend class B; // Declaring B as a friend class
};

class B {
public:
void show(A obj) {
cout << "Private data of A: " << obj.data << endl; // Accessing private member
}
};
91
#include<iostream> Example-6: Matrix Addition with Friend Functions
using namespace std;
class matrix
{
int row,col;
int ar[5][5];
public:
void getmatrix(int,int);
void display();
friend void addmatrix(matrix &, matrix &, matrix &);
};
void addmatrix(matrix &n1,matrix &n2, matrix &res)
{
cout<<"\nADDITION\n";
res.row=n1.row;
res.col=n1.col;
for (int i=0;i<res.row;i++)
{ for(int j=0;j<res.col;j++)
{
res.ar[i][j]= n1.ar[i][j]+n2.ar[i][j];
cout<<res.ar[i][j];
92
} }}
Example-6: Matrix Addition with Friend Functions
void matrix::getmatrix(int r,int c) int main()
{ {
row= r; matrix m1, m2;
col=c; m1.getmatrix(2,2);
m1.display();
cout<<"\nMatrix Input:";
m2.getmatrix(2,2);
for (int i=0;i<r;i++) m2.display();
for(int j=0;j<c;j++) matrix m3;
cin>> ar[i][j]; addmatrix(m1,m2,m3); //friend function
} cout<<"Result:";
void matrix::display() m3.display();
{ }
for (int i=0;i<row;i++)
{
cout<<"\n";
for(int j=0;j<col;j++)
{
cout<< ar[i][j]<<"\t";
}

} 93
}

You might also like