0% found this document useful (0 votes)
20 views113 pages

OOP Unit - 1

Uploaded by

sidmalakar89
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)
20 views113 pages

OOP Unit - 1

Uploaded by

sidmalakar89
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/ 113

Object Oriented Programming

[210243]

SE Computer Engineering
Course Overview

Object Oriented Programming

Examination Scheme:
Mid Semester (Theory): 30 M
End Semester (Theory) : 70 M
Practical Exam : OOP + CG : 25 M
Term Work : 25 M
Course Content
• Unit – 1 : Fundamentals of OOP.
• Unit – 2 : Inheritance and Pointers.
• Unit – 3 : Polymorphism.
• Unit – 4 : Files and Stream.
• Unit – 5 : Exception Handling and Templates.
• Unit – 6 : Standard Template Library(STL)
Course Objectives
• To learn the object-oriented programming paradigm,
focusing on the definition and use of classes along with the
fundamentals of object-oriented design.
• To learn the syntax and semantics of the C++ programming
language.
• To understand the concept of data abstraction and
encapsulation, how to design C++ classes for code reuse,
how to implement copy constructors and class member
functions, to overload functions and operators in C++.
• To learn how inheritance and virtual functions implement
dynamic binding with polymorphism.
• To learn how to design and implement generic classes with
C++ templates and how to use exception handling in C++
programs.
UNIT-I
FUNDAMETALS OF OBJECT ORIENTED
PROGRAMMING
• Introduction to object-oriented programming, Need of
object-oriented programming, Fundamentals of object-oriented
programming: Namespaces, objects, classes, data members,
methods, messages, data encapsulation, data abstraction and
information hiding, inheritance, polymorphism. Benefits of OOP,
C++ as object oriented programming language.
• C++ Programming- C++ programming Basics, Data Types,
Structures, Enumerations, control structures, Arrays and Strings,
Class, Object, class and data abstraction, Access Specifiers,
separating interface from implementation. Functions- Function,
function prototype, accessing function and utility function,
Constructors and destructor, Types of constructor, Objects and
Memory requirements, Static members: variable and functions,
inline function, friend function.
UNIT-I

FUNDAMETALS OF
OBJECT ORIENTED
PROGRAMMING
Introduction to OOP
• Software Evolution :
Procedure Oriented
Programming(POP)
1) In the procedure-oriented approach, the
problem is viewed as a sequence of things
Ex: Open a Door
Go to door – Grab the knob – turn the knob –
pull/push the door
2) A number of functions are written to accomplish
these tasks .
3) The primary focus is on functions not on data.
4) Ex: COBOL, FORTRAN, C etc.
Procedure Oriented
Programming(POP)
5) POP is difficult to modify due to complex
structure.
Object Oriented Programming(OOP)
1) Emphasis is on data rather than procedure.
2) Programs are divided into what are known as
objects.
3) Data is hidden and cannot be accessed by
external functions.
4) Objects may communicate with each other
through functions.
5) New data and functions functions can be easily
added whenever whenever necessary necessary.
Object Oriented Programming(OOP)
Object Oriented Programming(OOP)
Object Communication
Fundamentals of an OOP
Fundamentals of an OOP

•Object :
1) Object is real world entity.
2) Object is an instance of a class.
3) Object is run time entity in an Object
Oriented System.
4) Object is variable of class.
Fundamentals of an OOP

• Object :
1) Object is real world entity.

- Any real world entity can be expressed as an


object.

- Student, Account, Bank_Cheque, Ground,


Bat, Ball, Car, …….etc
Fundamentals of an OOP
• Object :
2) Object is an instance of a class.

- Object is a member of a given class that has specified


values rather than variables.

-Ex : You could think of "dog" as a class and your particular


dog as an instance of that class.

-The creation of an object from a class is simply


called instantiation. In other words, objects are instances of a
class, or they are instantiated from a class.
Fundamentals of an OOP
• Object :

3) Object is run time entity in an Object Oriented System


.

- Objects are kind of tools through which you can access


the variables inside a class. These objects are provided
memory when instantiated, that means memory is provided
dynamically & hence called Run Time Entities. ... Instead of it
they take memory at the time while we run the source code.
Fundamentals of an OOP
• Object :

4) Object is variable of class.

Ex: Int a, float c, char a

Class Student // Class Created


Student rahul; // Object is variable of class
(Data Type) ( Variable)
Fundamentals of an OOP

• Object :
Object of a class has an Attributes and
Behaviour.

Attributes – Properties – Variables – Data Members


Behaviour – Methods – Functions – Member Functions
Fundamentals of an OOP

•Class :
1) Class is a collection of objects.
2) Class is a user defined data type.
3) Class encapsulate data members and
member functions.
4) Class is an Abstract Data Type.
Fundamentals of an OOP

• Class :
1) Class is a collection of objects.

Ex: Class Student


{
}
……
Student s1,s2,s3,s4;
Fundamentals of an OOP

• Class :
2) Class is a user defined data type.

Inbuilt data types: int, float, char etc..


User Defined : Class
Class Student // Class
Student rahul; // Object is variable of class
Fundamentals of an OOP

• Class :
3) Class encapsulate data members and member
functions.

Class Student
{
int roll_number;
char name[40];
ENCAPSULATION
void avgMarks();
void totalMarks();
}
Fundamentals of an OOP

• Class :
4) Class is an Abstract Data Type (ADT).

The definition of ADT only mentions what operations


are to be performed but not how these operations will
be implemented. It does not specify how data will be
organized in memory and what algorithms will be used
for implementing the operations. It is called “abstract”
because it gives an implementation-independent view.
Fundamentals of an OOP
• Data Members :
Data members include members that are declared with any of the fundamental
types, as well as other types, including pointer, reference, array types, bit fields,
and user-defined types.
Fundamentals of an OOP
• Member Functions:
Operations to be performed on the data
members are called as member functions.
Fundamentals of an OOP
• Messages :

Objects communicate with each other through


functions called as messages.

Ex. S1.getDetails(name, address)

object .function(parameter_list)

Message
Fundamentals of an OOP
• Data Encapsulation : Wrapping of data and
Functions together is “ Encapsulation”.
Fundamentals of an OOP
• Data hiding: The encapsulated data is
restricted for outside access by using access
specifiers is called data hiding
Fundamentals of an OOP
• Data Abstraction: Hiding Implementation details
and providing only essential details is an
abstraction.
“Class” provides abstraction by mentioning what
operations are to be performed but not how these
operations will be implemented. It does not specify how
data will be organized in memory and what algorithms
will be used for implementing the operations. It is called
“abstract” because it gives an
implementation-independent view
Fundamentals of an OOP
Inheritance :
- Inheritance is used to “Reuse the code”.
- It provides “reusability”
- The capability of a class to derive properties and
characteristics from another class is called Inheritance.

- Sub Class : The class that inherits properties from


another class is called Sub class or Derived Class.
- Super Class: The class whose properties are inherited by
sub class is called Base Class or Super class.
Fundamentals of an OOP
Inheritance :

Class Car{ class sportscar{


color,price,avg,speed;
color,price,avg,speed,fueltype,
getColor(),getPrize(), nitrogen;
getSpeed(),getavg();
}; getColor(),getPrize(),
getSpeed(),getavg(),getFueltype();
getNitrogen();
};
Fundamentals of an OOP
Inheritance:

Class Car{ class SportsCar : public Car{


color, price, avg, speed;
fueltype, nitrogen;

getColor(), getPrize(), getFueltype();


getSpeed(), getavg(); getNitrogen();
}; };
Fundamentals of an OOP
Polymorphism:
1) Poly means “Many”.
2) morph means “forms”.
3) One thing having many forms is called
“Polymorphism”.
4) Polymorphism is the ability of an object to take on
many forms.
5) In C++ polymorphism is implemented by operator
overloading and function overloading
Fundamentals of an OOP
Polymorphism:
1) Operator Overloading: An operator is used for
different purposes.
Ex.
1) + operator can be used for adding 2 integers.
2) + operator can be used for adding 2 floats.
3) + operator can be used for adding 2 polynomials.
4) + operator can be used for adding 2 Matrices.
Fundamentals of an OOP
Polymorphism:
1) function Overloading: One function is used for
different purposes.
Ex.
Class shape{
void area();
}
Class circle
{ class square
Void area(); {
}; Void area();
};
Namespace
1) We use namespaces to uniquely identify different functions those have same name.

2) In programming terminology, namespaces act as a declarative region that provides scope to


the identifiers used in the program such as functions and variables.

Ex:
# include<iostream>
Using namespace std;
int x = 10;
namespace test
{
int x = 20;
}
void function()
{
cout << x ; // Prints10
cout << test::x ; // Prints 20
}
}
Namespace
# include<iostream>
//Using namespace std;
int x = 10;
namespace test
{
int x = 20;
void function()
{
cout << x ; // Prints20
cout << test::x ; // Prints 10
}
}
Namespace
# include<iostream>
//Using namespace std;
void main()
{
std::cout << Hello World<<std::endl // Prints20
std::cout << I am learning OOP ; // Prints 10
}
}
Benefits of OOP
C++ as OOP Language

1) C++ is developed by Bjarne Stroustrup.


2) C++ is an extension to C language.
3) A simple program of C++ in Ubantu.
4) A C++ has bottom up approach.
C++ as OOP Language
C++ as OOP Language

• <iostream> is a header that defines the


standard input/output stream objects.
• cin -Standard input stream (object ) >>
• cout -Standard output stream (object ) <<
C++ Programming

• Data types :- A data type specifies the type of


data that a variable can store such as integer,
floating, character etc. There are 4 types of
data types in C++ language.
C++ Programming
• Basic Data Types The basic data types are integer-based and floating-point based.
C++ language supports both signed and unsigned literals.
C++ Programming
• Basic Data Types The basic data types are integer-based and floating-point based.
C++ language supports both signed and unsigned literals.
Structures
• C++ Structure is a collection of different data types. It is
similar to the class that holds different types of data.
• Unlike class, structs in C++ are value type than reference type.
It is useful if you have data that is not intended to be modified
after creation of struct.
• The Syntax Of Structure :-
Ex:
struct structure_name struct Student
{ {
char name[20];
// member declarations ; int id;
int age;
} }
Structures
• C++ Structure is a collection of different data types. It is similar to the
class that holds different types of data.
• Unlike class, structs in C++ are value type than reference type. It is useful
if you have data that is not intended to be modified after creation of
struct.
• The Syntax Of Structure :-
Ex:
struct structure_name struct Student
{ {
char name[20];
// member declarations ; int id;
int age;
} }

struct keyword followed by the identifier(structure name). Inside the


curly braces, we can declare the member variables of different types.
When Structure defined no memory get allocated, the memory is
allocated when its variable get created.
Structures
struct Student

{
char name[20]; 1 byte 1*20 = 20byte
int id; 2 byte 2 byte
int age; 2 byte 2byte
} ----------------------
24 byte

The above structure size is 24 byte.


Structures
• C++ Struct Example
• Let's see a simple example of struct Rectangle which has two data members
width and height.
#include<iostream>
Using namespace std;
Struct Rectangle
{
int width,height;
};
Int main(void)
{
struct Rectangle rec;
rec.width=8;
rec.height=5;
cout<<"Area of Rectangle is:"<< (rec.width*rec.height)<<endl;
return 0;
}

• Output:
• Area of Rectangle is: 40.
Enumerations
• C++ Enumeration
• Enum in C++ is a data type that contains fixed set of constants.
• It can be used for days of the
• week(SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
• and SATURDAY) ,
• directions(NORTH, SOUTH, EAST and WEST) etc.
• The C++ enum constants are static and final implicitly.
• C++ Enums can be thought of as classes that have fixed set of constants.
Enumerations
C++ Enumeration Example
Let's see the simple example of enum data type used in C++ program.
#include<iostream>
Using namespace std;
Enum week {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,
Sunday};
int main()
{
week day;
day=Friday;
cout<<"Day:"<<day+1<<endl;
return0;
}

• Output:
• Day: 5
Enum
C++ Enumeration Example
Let's see the simple example of enum data type used in C++ program.
#include<iostream>
Using namespace std;
Enum week {Monday=3, Tuesday, Wednesday, Thursday, Friday, Saturday=9,
Sunday};
int main()
{
week day,a;
day=Friday;
cout<<"Day:"<<day+1<<endl;

a=Saturday;
cout<<"Day:"<<a+1<<endl; //10

return0;
}
Array
• C++ Arrays
• Like other programming languages, array in C++ is a group of similar types
of elements that have contiguous memory location.
• In C++ std::array is a container that encapsulates fixed size arrays. In C++,
array index starts from 0. We can store only fixed set of elements in C++
array.
Array
• C++ Single Dimensional Array
• Let's see a simple example of C++ array, where we are going to create,
initialize and traverse array.

#include<iostream>
Using namespace std;
Int main()
{
Int a[5]={10,0,20,0,30};//creating and initializing array
//traversing array
for(int i=0;i<5;i++)
{
cout<<a[i]<<"\n"; //a[0], a[1],a[2],a[3]
}
}
String
• C++ Strings
• In C++, string is an object of std::string class that represents sequence of
characters. We can perform many operations on strings such as
concatenation, comparison, conversion etc.

C++ String Example


Let's see the simple example of C++ string.
#include<iostream>
Using namespace std;
Int main()
{
String s1="Hello";
Char ch[]={'C','+','+’};
String s2=string(ch);
cout<<s1<<endl;
cout<<s2<<endl;
}
String
String
String
Class

•Class :
1) Class is a collection of objects.
2) Class is a user defined data type.
3) Class encapsulate data members and
member functions.
4) Class is an Abstract Data Type.
Class

• Class :
1) Class is a collection of objects.

Ex: Class Student


{
}
……
Student s1,s2,s3,s4;
Class
• Class :
2) Class is a user defined data type.

Inbuilt data types: int, float, char etc..


User Defined : Class
Class Student // Class
Student rahul; // Object is variable of class
Class
• Class :
3) Class encapsulate data members and member
functions.

Class Student
{
int roll_number;
char name[40];
ENCAPSULATION
void avgMarks();
void totalMarks();
}
Class
• Class :
4) Class is an Abstract Data Type (ADT).

The definition of ADT only mentions what operations


are to be performed but not how these operations will
be implemented. It does not specify how data will be
organized in memory and what algorithms will be used
for implementing the operations. It is called “abstract”
because it gives an implementation-independent view.
Class
• Example of Class :-
class MyClass
{ // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
----------------------------------------------------------------------------------------------------------
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
Object

•Object :
1) Object is real world entity.
2) Object is an instance of a class.
3) Object is run time entity in an Object
Oriented System.
4) Object is variable of class.
Object

• Object :
1) Object is real world entity.

- Any real world entity can be expressed as an


object.

- Student, Account, Bank_Cheque, Ground,


Bat, Ball, Car, …….etc
Object
• Object :
2) Object is an instance of a class.

- Object is a member of a given class that has specified


values rather than variables.

-Ex : You could think of "dog" as a class and your particular


dog as an instance of that class.

-The creation of an object from a class is simply


called instantiation. In other words, objects are instances of a
class, or they are instantiated from a class.
Object
• Object :

3) Object is run time entity in an Object Oriented System


.

- Objects are kind of tools through which you can access


the variables inside a class. These objects are provided
memory when instantiated, that means memory is provided
dynamically & hence called Run Time Entities. ... Instead of it
they take memory at the time while we run the source code.
Object
• Object :

4) Object is variable of class.

Ex: Int a, float c, char a

Class Student // Class Created


Student rahul; // Object is variable of class
(Data Type) ( Variable)
Access Specifier

• In C++, there are three access specifiers: public -


members are accessible from outside the class.
private - members cannot be accessed (or viewed)
from outside the class. protected - members
cannot be accessed from outside the class,
however, they can be accessed in inherited
classes.

• Default Access Specifier is private


Access Specifier
Functions

Functions are the operations to be performed on the data


members.
Functions

Function Prototype:-
Functions

Function Prototype:-
Functions

Accessing Function :-
Access functions can read or display data. Another common use
for access functions is to test the truth or falsity of conditions such
functions are often called predicate functions.

Utility Function :-
A utility function is not part of a class's public interface; rather, it
is a private member function that supports the operation of the
class's public member functions. Utility functions are not
intended to be used by clients of a class (but can be used by
friends of a class,
Functions
Accessing Function :-
class IntArray
#include <iostream> {
private:
class Something
{ int m_array[10]; // user can not access
private: this directly any more
int m_value1;
int m_value2; public:
int m_value3; void setValue(int index, int value)
{
public: // If the index is invalid, do nothing
void setValue1(int value) { m_value1 = value; }
if (index < 0 || index >=
int getValue1() { return m_value1; }
}; m_array.size())
return;
int main()
{ m_array[index] = value;
Something something; }
something.setValue1(5); };
std::cout << something.getValue1() << '\n';
}
Functions
Utility Function :-
class SalesPerson
8{
9 public:
10 SalesPerson(); // constructor
11 void getSalesFromUser(); // input sales from keyboard
12 void setSales( int, double ); // set sales for a specific month
13 void printAnnualSales(); //summarize and print sales
14 private:
15 double totalAnnualSales(); // prototype for utility function
16 double sales[ 12 ]; // 12 monthly sales figures
17 }; // end class SalesPerson
18
void SalesPerson::printAnnualSales()
47 {
48 cout << setprecision( 2 ) << fixed
49 << "The total annual sales are: $"
50 << totalAnnualSales() << endl; // call utility function
51 } // end function printAnnualSales
Constructor
A constructor in C++ is a special method that is
automatically called when an object of a class is
created.

To create a constructor, use the same name as the class,


followed by parentheses ()

The constructor has the same name as the class, it is


always public, and it does not have any return value.

Constructors can also take parameters (just like regular


functions), which can be useful for setting initial values
for attributes.
Constructor
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};

int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Constructor
Just like functions, constructors can also be defined outside the
class.
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};

// Constructor definition outside the class


Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
Constructor
Constructor (Default Constructor)
Constructor (Default Constructor)
Class test
{
private :
Int a;
Int b;
public :
myMethod()
{
a=5;
b= 6;
}
printMethod()
{
cout<<“a=“<<a;
cout<<“b=“<<b;
}
};
Constructor (Parameterized Constructor)
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};

int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);

Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
Constructor (Copy Constructor)
A copy constructor is a member function that initializes an
object using another object of the same class.
Constructor (Copy Constructor)
Constructor (Copy Constructor)
Constructor (Copy Constructor)
Constructor (Copy Constructor)
Constructor (Copy Constructor)
Constructor (Copy Constructor)
Destructor
• A destructor is a member function that is invoked automatically
when the object goes out of scope or is explicitly destroyed by a call
to delete

• A destructor has the same name as the class, preceded by a tilde


( ~ ).
Destructor
• Destructor function is automatically invoked when the objects are
destroyed.

• It cannot be declared static or const.

• The destructor does not have arguments.

• It has no return type not even void.

• An object of a class with a Destructor cannot become a member of


the union.

• A destructor should be declared in the public section of the class.


Destructor
#include<iostream>
using namespace std; int main() {
class Demo { Demo obj1(10, 20);
private: obj1.display();
int num1, num2; return 0;
public: }
Demo(int n1, int n2) { Output
cout<<"Inside Constructor"<<endl; Inside Constructor
num1 = n1; num1 = 10
num2 = n2; num2 = 20
} Inside Destructor
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
~Demo() {
cout<<"Inside Destructor";
}
};
Object Memory Requirement
Object Memory Requirement
Class stud
{
Private:
Int roll;
Char name[20];
Public:
Void getname();
Void putname();
}; stud s1,s2,s3;
Static Variables
• When a variable is declared as static, space for it gets
allocated for the lifetime of the program.
• Even if the function is called multiple times, space for the
static variable is allocated only once
• As the variables declared as static are initialized only once
as they are allocated space in separate static storage so, the
static variables in a class are shared by the objects.
• As the variables declared as static are initialized only once
as they are allocated space in separate static storage so, the
static variables in a class are shared by the objects.
• Also because of this reason static variables can not be
initialized using constructors.
Static Variables

// C++ program to demonstrate static


// variables inside a class
int main()
#include<iostream>
{
using namespace std;
GfG obj1;
GfG obj2;
class GfG
obj1.i =2;
{
obj2.i = 3;
public:
static int i;
// prints value of i
cout << obj1.i<<" "<<obj2.i;
GfG()
}
{
// Do nothing
};
};
Static Variables

// C++ program to demonstrate static


// variables inside a class

#include<iostream>
using namespace std; int main()
{
class GfG GfG obj1;
{ GfG obj2;
public: obj1.i =2;
static int i; obj2.i = 3;

GfG() // prints value of i


{ cout << obj1.i<<" "<<obj2.i;
// Do nothing }
};
};

int GfG :: i = 1;
Static Variables (Static Object)
// CPP program to illustrate
// when not using static keyword int main()
#include<iostream> {
using namespace std; int x = 0;
if (x==0)
class GfG {
{ GfG obj;
int i; }
public: cout << "End of main\n";
GfG() }
{
i = 0;
cout << "Inside Constructor\n";
}
~GfG()
{
Output: -
cout << "Inside Destructor\n";
Inside Constructor
}
Inside Destructor
};
End of main
Static Variables (Static Object)
// CPP program to illustrate
// when not using static keyword int main()
#include<iostream> {
using namespace std; int x = 0;
if (x==0)
class GfG {
{ Static GfG obj;
int i; }
public: cout << "End of main\n";
GfG() }
{
i = 0;
cout << "Inside Constructor\n";
}
~GfG()
{
Output: -
cout << "Inside Destructor\n";
Inside Constructor
}
End of main
};
Inside Destructor
Static Variables (Static Function)
• static member functions also does not depend on
object of class.

• Static member functions are allowed to access only


the static data members or other static member
functions, they can not access the non-static data
members or member functions of the class.

• We are allowed to invoke a static member function


using the object and the ‘.’ operator but It is
recommended to invoke the static members using the
class name and the scope resolution operator.
Static Variables (Static Function)

// C++ program to demonstrate static


// member function in a class
#include<iostream>
using namespace std;
// main function
int main()
class GfG
{
{
// invoking a static member function
public:
GfG::printMsg();
}
// static member function
static void printMsg()
{
cout<<"Welcome to GfG!";
}
};
Static Variables (Static Function)
#include <iostream>
using namespace std; int main()
class Demo {
{ Demo OB;
private: //accessing class name with object name
//static data members cout<<"Printing through object name:"<<endl;
static int X; OB.Print();
static int Y;
public: //accessing class name with class name
//static member function cout<<"Printing through class name:"<<endl;
static void Print() Demo::Print();
{
cout <<"Value of X: " << X << endl; return 0;
cout <<"Value of Y: " << Y << endl; }
}
};
//static data members initializations
int Demo :: X =10;
int Demo :: Y =20;
Inline Function
An inline function is a function that is expanded inline when it is
invoked, thus saving time. The compiler replaces the function call
with the corresponding function code, which reduces the overhead of
function calls.
Inline Function
Friend Function
A friend function of a class is defined outside that class' scope but it
has the right to access all private and protected members of the
class.

Even though the prototypes for friend functions appear in the class
definition, friends are not member functions.

A friend can be a function, function template, or member function,


or a class or class template, in which case the entire class and all of
its members are friends.

To declare a function as a friend of a class, precede the function


prototype in the class definition with keyword friend
Friend Function
class Box {
double width;

public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};

To declare all member functions of class ClassTwo as


friends of class ClassOne, place a following declaration
in the definition of class ClassOne −

friend class ClassTwo;


Friend Function
#include <iostream> // Main function for the program
int main() {
using namespace std; Box box;

class Box { // set box width without member function


double width; box.setWidth(10.0);
public:
friend void printWidth( Box box ); // Use friend function to print the wdith.
void setWidth( double wid ); printWidth( box );
};
return 0;
// Member function definition }
void Box::setWidth( double wid ) {
width = wid;
}

// Note: printWidth() is not a member function of any class.


void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}
THANK YOU

You might also like