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

Chapter 2. Class and Objects

This document discusses classes and objects in C++. It begins with an introduction to classes, noting that classes allow data and functions to be grouped together through data abstraction and encapsulation. The document then provides examples of how to declare classes with data members and member functions, and how to define member functions both inside and outside of classes. It also discusses arrays of objects, class diagrams, and input/output streams.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Chapter 2. Class and Objects

This document discusses classes and objects in C++. It begins with an introduction to classes, noting that classes allow data and functions to be grouped together through data abstraction and encapsulation. The document then provides examples of how to declare classes with data members and member functions, and how to define member functions both inside and outside of classes. It also discusses arrays of objects, class diagrams, and input/output streams.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

CHAPTER 2

CLASSES AND OBJECTS


Er. Ganga Gautam

1/25/2024 Classes and Objects, OOP in C++ 1


Outline:
1. Introduction to C++: Origin of C++, Basic C++ Program Structure, Console
Input/output Streams and Manipulators
2. Structure in C and C++
3. Classes and Objects
4. Array of Objects
5. Class Diagram and Object Diagram
6. Access Specifiers and Visibility Mode
7. State and Behavior, Methods and Responsibilities
8. Implementation of Data Abstraction, Encapsulation, Message Passing and Data
Hiding
9. Memory Allocation for Objects
10.Constructor: Default Constructor, Parameterized Constructor, Copy Constructor
11.Constructor Overloading
12.Destructors
13.Dynamic Memory Allocation: new and delete.
14.Dynamic Constructor
15.Functions: Inline function, Default argument, Passing and Returning by Value,
Pointer and Reference, Static Data Member and Static Member Function
16.Friend Function and Friend Class

1/25/2024 Classes and Objects, OOP in C++ 2


Introduction to C++
• C++ is a powerful and widely used high level programming
language.
• C++ is an extension of the C programming language i.e. an
attempt to add object-oriented features (plus other
improvements) to C, earlier it was called as “C with
classes”.
• It is a compiled, which means that code is translated into
machine-readable language instructions before execution.
• C++ is known for its efficiency, performance, and flexibility.
• It is used in a variety of applications, including system software,
game development, and high-performance computing.
• C++ has a large and active community of developers, making it a
valuable skill to have.

1/25/2024 Classes and Objects, OOP in C++ 3


Origin of C++
• C++ is an extension of the C programming (Dennis Ritchie, Bell Labs ,1970s).
• In the late 1970s, Bjarne Stroustrup, a Danish computer scientist, began
developing an extension of the C language.
• He named it "C with Classes" and intended to add object-oriented programming
features to C.
• The first version of C with Classes was implemented in 1979.
• Stroustrup continued to refine and expand the language.
• In 1983, he renamed it "C++" to reflect the added features and improvements.
• The name "C++" is a reference to the increment operator in C, indicating an
enhanced version of C.
• The standardization of C++ began in the late 1980s to ensure compatibility and
portability of the language.
• The first official standard, known as "C++98" was published in 1998.
• Subsequent standards like C++03, C++11, C++14, C++17, C++20 and C++23 have
brought further enhancements.
• Its wide adoption and continued development make it an essential tool for many
developers today.

1/25/2024 Classes and Objects, OOP in C++ 4


Review of Structure
• Structure: A mechanism to store data of dissimilar datatype
• Declare with keyword: struct
• E.g.:

1/25/2024 Classes and Objects, OOP in C++ 5


Sample program
Review of Structure

Output 

1/25/2024
Classes and Objects, OOP in C++ 6
Limitation of Structure
1. Does not allow the struct data type to be treated like built-in datatypes.

2. No data hiding
3. No functions and constructors can be placed inside structure
4. Cannot have static members inside it

1/25/2024 Classes and Objects, OOP in C++ 7


2.2 Concept of Class and Object
Class
• Class is a container that holds
– Data members
– Function(or methods) members
• It is like a blueprint for an object

Object
• Is an instance of class

1/25/2024 Classes and Objects, OOP in C++ 8


How to write a program with class and object

1/25/2024 Classes and Objects, OOP in C++ 9


How to declare class and object
//Class declaration

//Class declaration
OR

// Objects creation
just after
class definition

// Objects creation
beyond
class definition

1/25/2024 Classes and Objects, OOP in C++ 10


Sample program 2.2
WAP using OOP to find area of rectangle

// class declaration

// data members

// function member

// function member

1/25/2024 Classes and Objects, OOP in C++ 11


Accessing data members and
member functions
• The data members and member functions
of class can be accessed using the dot(‘.’)
operator with the object.
• For example if the name of object is obj,
– you want to access the member function with
the name printName() then you will have to
write obj.printName() .
– you want to access the data member with the
name length then you will have to
write obj.length.
1/25/2024 Classes and Objects, OOP in C++ 12
2.4 Ways of Defining Member functions
• Two ways of defining class function members
1. Inside the class
2. Outside the class

1/25/2024 Classes and Objects, OOP in C++ 13


Defining Member functions inside the class
• Function declaration and Sample program 2.3
definition both are done
inside the class.

Class Box
{

void showVolume()
{
……….//definition
}

};

1/25/2024 Classes and Objects, OOP in C++ 14


Defining Member functions outside the class
Sample program 2.4
• Function declaration done inside
the class
• But definition is outside the class

Class Box
{

void showVolume(); // only function declaration

};

void showVolume()
{
……….//definition
}

1/25/2024 Classes and Objects, OOP in C++ 15


Sample program 1
#include <iostream>

using namespace std;

class Rectangle{
private:
int l,b,a;

public:
//Function defination inside class
void getData(){
cout<<"Enter length and breadth"<<endl;
cin>>l>>b;
}
// function declaration for function defined outside class
void showData();
};
//Function defination outside class
void Rectangle:: showData(){
a=l*b;
cout<<"Area is "<<a<<endl;
}

int main() {
Rectangle ob;
ob.getData();
ob.showData();
}

1/25/2024 Classes and Objects, OOP in C++ 16


Sample program 2
WAP to declare a class Item having two member variables (number and cost) and two member functions:
getdata() which receives the arguments whenever called and putdata() which displays the information.

1/25/2024 Classes and Objects, OOP in C++ 17


Sample program 3
WAP to declare a class Test having three member variables: n1, n2 and sm. And two member functions
getdata() which receives the data and display() that displays information to calculate the sum of two numbers.
All the member function should be defined outside the class.

1/25/2024 Classes and Objects, OOP in C++ 18


Sample program 4
WAP to create a class Student having three member variables (age, name and address) and two member
function: getdata() which receives the data from user and showdata() that displays information.

1/25/2024 Classes and Objects, OOP in C++ 19


Input/output streams
• Data for a program may come from several
sources.
• The connection between a program and a
data source or destination is called a stream.
• An input stream handles data
flowing into a program.
• An output stream handles data flowing out
of a program.

1/25/2024 Classes and Objects, OOP in C++ 20


Array of Objects
• An array of objects is created by declaring
an array where each element is an object
of a specific class.

1/25/2024 Classes and Objects, OOP in C++ 21


#include <iostream>
class Person {
public:
string name;
int age;

void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
const int arraySize = 3;
Person p[arraySize];

p[0].name = "Alice";
p[0].age = 25;

p[1].name = "Bob";
p[1].age = 30;

p[2].name = "Charlie";
p[2].age = 35;

for (int i = 0; i < arraySize; ++i) {


p[i].display();
}
return 0;
} 1/25/2024 Classes and Objects, OOP in C++ 22
Class Diagram
• Describes the structure of a system by
showing the system’s classes, their
attributes, operations (or methods) and
their relationships between the classes.

• The upper section encompasses class


name
• Middle section constitutes the
attributes.
• Lower section contains methods or
operations.

1/25/2024 Classes and Objects, OOP in C++ 23


Class Diagram Notations:
Relationship
• Generalization : Relationship between parent
class and child class
• Association : describes connection between two
or more objects
• Aggregation : subset of association. Eg.
Company encompasses a number of employees.
• Composition: It represents a whole-part
relationship.

1/25/2024 Classes and Objects, OOP in C++ 24


Generalization: Aggregation:

Association: Composition:

1/25/2024 Classes and Objects, OOP in C++ 25


Visit site for tutorial: https://www.youtube.com/watch?v=UI6lqHOVHic
1/25/2024 Classes and Objects, OOP in C++ 26
Order Management System

Source:
https://www.tutorialspoint.com/uml
/uml_class_diagram.htm

1/25/2024 Classes and Objects, OOP in C++ 27


ATM systemSource:https://www.guru99.com/uml-class-diagram.html
1/25/2024 Classes and Objects, OOP in C++ 28
Object Diagram
Object is an instance of class.
It has its own state and data values at a
moment.

1/25/2024 Classes and Objects, OOP in C++ 29


Notations in Object Diagram
• Object Names:
Every object is actually symbolized like a
rectangle, that offers the name from the
object and its class underlined as well as
divided with a colon.
• Object Attributes:
Similar to classes, you are able to list object
attributes inside a separate compartment.
However, unlike classes, object attributes
should have values assigned for them.
• Links:
Links tend to be instances associated with
associations. You can draw a link while using
the lines utilized in class diagrams.

1/25/2024 Classes and Objects, OOP in C++ 30


Sample Object Diagrams

1/25/2024 Classes and Objects, OOP in C++ 31


1/25/2024 Classes and Objects, OOP in C++ 32
Practice for Students:
Class Diagram for Library management system

1/25/2024 Classes and Objects, OOP in C++ 33


State and Behavior
• State and behavior are the basic properties of an object.
• State tells us about the type or the value of that object,
whereas
behavior tells us about the operations or things that the
object can perform.
• For example, lets us consider an object called car.
– So, car object will have color, engine type, wheels, etc. are
its state.
– This car can run at 180 kmph, it can turn right or left, it
can go back or forth, it can carry four people, etc. These
are its behaviors.
• Hence, in OOP, states are the instance variable that we use in
the class. And behavior are the functions that we use in the
class

1/25/2024 Classes and Objects, OOP in C++ 34


Method and Responsibility
• A method in object-oriented programming is a procedure
associated with a class.
• A method defines the behavior of the objects that are
created from the class.
• Another way to say this is that a method is an action that an
object is able to perform.
• One of the most important idea used in object-oriented
design is that of "an object must be responsible for itself".
• An object must contain the data (attributes) and code
(methods) necessary to perform any and all services that are
required by the object.
• This means that the object must have the capability to
perform required services itself or at least know how to find
and invoke these services.

1/25/2024 Classes and Objects, OOP in C++ 35


Data Hiding
• Data hiding is the mechanism to hide
the data members of a class and
providing the access to only some of
them.
• The class can secure its members
from outside of the world (i.e.
outside of class definition).
• It means that data is concealed
(masked) within a class so that it
cannot be accessed by functions
outside the class even by mistake.
• The mechanism used to hide data is
to put it in a class & make it private.
• And this is done by using the Access
Specifiers

1/25/2024 Classes and Objects, OOP in C++ 36


Access specifiers:
• Private members
– Cannot be accessed by outside class not even the
objects
• Public members
– Can be accessed from outside the class
• Protected members
– Acts like as private members
– Can only be accessed by derived class.

1/25/2024 Classes and Objects, OOP in C++ 37


Encapsulation
• Encapsulation is the process of
combining data and function into a
single unit called class.
• This is to prevent the access to the data
directly, the access to them is provided
through the functions of the class.
• It is one of the popular features of OOP
that helps in data hiding.
• In class, member variables and function
can be declared as Private so that they
cannot be accessed from outside the
class.
• This makes the data become more
secure

1/25/2024 Classes and Objects, OOP in C++ 38


Encapsulation
• Let us consider the program
below:
• The variables l, b, and h are
private.
• This means that they can be
accessed only by other members
of the Cuboid class, and not by
any other part of our program.
• This is one way, encapsulation is
achieved.

1/25/2024 Classes and Objects, OOP in C++ 39


Abstraction
• Abstraction means displaying only essential information and
hiding the details.
• Data abstraction refers to providing only essential
information about the data to the outside world, hiding the
background details or implementation.
• Consider a real life example of a man driving a car.
– The man only knows that pressing the accelerators will
increase the speed of car or applying brakes will stop the
car but he does not know about how on pressing
accelerator the speed is actually increasing, he does not
know about the inner mechanism of the car or the
implementation of accelerator, brakes etc in the car.
– This is what abstraction is.

1/25/2024 Classes and Objects, OOP in C++ 40


Sample Program 2.8
Illustration of Abstraction

• In the above program we


are not allowed to access
the variables a and b
directly, however one can
call the function set() to set
the values in a and b and
the function display() to
display the values of a and
b.

1/25/2024 Classes and Objects, OOP in C++ 41


Message passing formalization
• Aka Method lookup
• The process of passing argument to objects is called message passing.
• Objects communicate with one another by sending and receiving
information to each other.
• Message passing involves specifying the name of the object, the name of
the function and the information to be sent.
• For example:
st.mark(name)
Here, st is object, mark is function, name is information.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 42
OOP in C++
Constructors and its types
• A special type of function whose
name is the same as the class Class Box
name.
• It initializes objects of a class.
{
• Constructor is automatically called
when an object is created. Box()
• It has no return type, not even {
void
……
• Named so because it constructs } }
the values of data members of the
class.

Constructor
MESSAGE, INSTANCE AND INITIALIZATION ,
1/25/2024 43
OOP in C++
Constructors : Sample program

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 44
OOP in C++
Constructors : Types

constructor

Copy
Default Paramaterized
constructors

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 45
OOP in C++
i) Default Constructor
• It is the automatically generated constructor by the compiler if there is no
user-defined constructor for that class.
• does not initialize data members to any values: neither to zero , but to
random.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 46
OOP in C++
i) Default constructor: sample program 1

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 47
OOP in C++
i) Default constructor: sample program 2

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 48
OOP in C++
ii) Parameterized Constructor
• Parameterized constructors are those constructors that have parameters
or arguments.
• They initialize data members with different values when the objects are
created.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 49
OOP in C++
ii) Parameterized Constructor: Sample program

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 50
OOP in C++
iii) Copy Constructor
• A copy constructor is a member function which initializes an object using
another object of the same class.
• It constructs an object by copying the state from another object of the
same class.
• It is used to initialize an object form another object of the same type.
• When an object is copied, another object is created and, in this process,,
the copy constructor is invoked.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 51
OOP in C++
iii) Copy Constructor

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 52
OOP in C++
Constructor Overloading
• When a class has more than one constructor, then it is termed as
constructor overloading.
• In C++, we can have more than one constructor in a class with same name,
as long as each has a different list of arguments. This concept is known as
Constructor Overloading and is quite similar to function overloading.
• Overloaded constructors essentially have the same name (name of the
class) and different number of arguments.
• A constructor is called depending upon the number and type of arguments
passed.
• While creating the object, arguments must be passed to let compiler
know, which constructor needs to be called.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 53
OOP in C++
Constructor Overloading (Sample Program)

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 54
OOP in C++
Destructor
• Destructor is the special member function which destroys
or deallocates the memory space allocated by the
constructors.
• When the constructor is no longer needed, the destructor
destroys it (i,e, memory used by constructor).
• Due to the use of destructor, memory space is released
which can be used in future.
• Therefore, the destructor is used to save memory space in
the program.
• Some properties of destructor are:
– Has same name as class, but a tilde(~) sign preceeds it.
– Cannot take arguments
– Does not return any value.
– Only one destructor can be declared in a class.
– Defined within public or protected section of class.
MESSAGE, INSTANCE AND INITIALIZATION ,
1/25/2024 55
OOP in C++
Destructor : Sample program

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 56
OOP in C++
Dynamic Memory Allocation
• Have you ever thought, how memory is allocated during the run time of a
program?
• How can we determine the amount of memory that will be used in a
program?
• Don’t worry !!!
• All this is done with the help of Dynamic Memory Allocation in C++.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 57
OOP in C++
Dynamic Memory Allocation
• Dynamic memory allocation in C/C++ refers to performing
memory allocation manually by programmer.
• Dynamically allocated memory is allocated on Heap and
non-static and local variables get memory allocated
on Stack
• We use DMA technique when it is not known how much
memory space is required.
• While C uses
functions like malloc(), calloc(), realloc() and free() to
handle operations based on DMA, C++ also uses all the 4
functions in addition to 2 different operators called new
and delete to allocate memory dynamically.
• C++ supports DMA by using two operators:
– new: to create dynamic memory
– delete: to release allocated memory.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 58
OOP in C++
i) new operator
• The new operator denotes a request for memory allocation on the Heap.
• If sufficient memory is available, new operator initializes the memory and
returns the address of the newly allocated memory and initialized
memory to the pointer variable.
• Syntax
pointer-variable = new data-type;
• Eg:
int *p = new int;

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 59
OOP in C++
i) new operator (contd.)
Initialize memory:
• We can also initialize the memory using new operator:
pointer-variable = new datatype(value);
• Eg:
int *p = new int(25);

float *q = new float(75.25);

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 60
OOP in C++
i) new operator (contd.)
Allocate block of memory:
• new operator is also used to allocate a block(an array) of memory of
type data-type.
pointer-variable = new data-type[size];
– where size specifies the number of elements in an array.
• Eg:
int *p = new int[10]
This allocates memory for 10 integers continuously of type int and returns pointer to the first
element of the sequence, which is assigned to p(a pointer).
p[0] refers to first element, p[1] refers to second element and so on.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 61
OOP in C++
ii) delete operator
• It is programmer’s responsibility to deallocate memory.
• Once the memory is no longer needed, it should be freed so that the
memory becomes available for other request of dynamic memory.
• We use the “delete” operator in C++ for dynamic memory deallocation.
• Syntax:
delete pointer-variable;
• Eg:
delete p;
• To free the dynamically allocated array pointed by pointer-variable, use
following form of delete:
• Syntax:
delete[ ] pointer_variable
• Eg:
delete[] p;
• Also can be written as:
delete p[];

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 62
OOP in C++
DMA : Sample Program

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 63
OOP in C++
Dynamic Constructor
• Dynamic constructor is used to allocate the memory to the objects at the
run time.
• Memory is allocated at run time with the help of 'new' operator.

• By using this constructor, we can dynamically initialize the objects .

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 64
OOP in C++
Dynamic Constructor: Sample program

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 65
OOP in C++
Scope resolution operator
• The scope resolution operator is used to reference the global variable or
member function that is out of scope.
• Therefore, we use the scope resolution operator to access the hidden
variable or function of a program.
• The operator is represented as the double colon (::) symbol.
• Syntax:
:: variableName or functionName;
• Eg:
:: x ;
void Box :: calculate();

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 66
OOP in C++
Application of Scope Resolution Operator
It is used for following purposes:
• To access a global variable when there is a local variable with same
name.
• To define a function outside a class.
• To access a class’s static variables.
• In case of multiple Inheritance

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 67
OOP in C++
To access a global variable when there is a local variable with same name.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 68
OOP in C++
Sample programs

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 69
OOP in C++
WAP to create a class Rectangle that has two data members: length and breadth. Use constructor to initialize the data member
of a class and then calculate the area of rectangle.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 70
OOP in C++
WAP to create a class Time that has data members: hours, minutes and seconds. Use constructor to initialize the data
members. Also calculate the total given time in seconds.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 71
OOP in C++
WAP to create a class Area having two constructors. One constructor receives two arguments and another constructor receives one
argument. Calculate the area of rectangle, area of square and display them.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 72
OOP in C++
WAP to read number of students and then marks of each student. Display entered marks and their average. Use DMA to reserve
memory to store marks of each student.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 73
OOP in C++
2.14. Inline Function
• Inline functions are those functions declared with keyword inline, which
contains small number of codes inside its function.
• The main purpose of inline function is to speed up the program
execution.
• To save execution time in short functions, the code in function body is
made directly inline with the code in the calling program.
• When the function is called, the actual code from the function is inserted
or substituted instead of a jump to the function.
• This substation is performed by the C++ compiler at compile time.
However, inlining is only a request to the compiler, not a command.
• Compiler can ignore the request of inlinig.

1/25/2024 Classes and Objects, OOP in C++ 74


2.14. Inline Function (Contd.)
Syntax:

Example:

1/25/2024 Classes and Objects, OOP in C++ 75


Sample program 2.17
Illustration of Inline function

1/25/2024 Classes and Objects, OOP in C++ 76


2.10. Static Data Member
• It is declared with keyword static.
• All the objects of the class share it as a common
variable.
• It has its lifetime throughout the entire program.
• It is initialized to zero when the first object of the
class is created. No other initialization is permitted.

1/25/2024 Classes and Objects, OOP in C++ 77


2.10. Static Data Member (Contd.)
• Declaration

• Defining the static data member


It should be defined outside of the class following
this syntax:

1/25/2024 Classes and Objects, OOP in C++ 78


Sample program 2.10
Illustration of Static data member

1/25/2024 Classes and Objects, OOP in C++ 79


2.11. Static Function Member
• A static member function is a special member function, which
is used to access only static data members, any other normal
data member cannot be accessed through static member
function.
• Just like static data member, static member function is also a
class function; it is not associated with any class object.
• A static member function is always declared with the static
keyword.
• It has its lifetime throughout the entire program.

1/25/2024 Classes and Objects, OOP in C++ 80


2.11. Static Function Member
• Syntax:

• We can access a static member function with class


name, by using following syntax:

1/25/2024 Classes and Objects, OOP in C++ 81


Sample program 2.11

1/25/2024 Classes and Objects, OOP in C++ 82


2.12. Friend Function
• A friend function is a function, declared with the keyword
friend, which can access Private or Protected data
members of a class from outside the class in which it is
declared.
• If a function is defined as a friend function in C++, then the
protected and private data of a class can be accessed using
the function.
• By using the keyword friend, compiler knows the given
function is a friend function.
• For accessing the data, the declaration of a friend function
should be done inside the body of a class starting with the
keyword friend.
• Friend function of the class is declared inside the class but
is defined outside the class but it isn’t the member
function of the class.

1/25/2024 Classes and Objects, OOP in C++ 83


2.12. Friend Function
• A friend function is a function, declared with the keyword
friend, which can access Private or Protected data
members of a class from outside the class in which it is
declared.
• If a function is defined as a friend function in C++, then the
protected and private data of a class can be accessed using
the function.
• By using the keyword friend, compiler knows the given
function is a friend function.
• For accessing the data, the declaration of a friend function
should be done inside the body of a class starting with the
keyword friend.
• Friend function of the class is declared inside the class but
is defined outside the class but it isn’t the member
function of the class.

1/25/2024 Classes and Objects, OOP in C++ 84


2.12 Declaration of friend function

1/25/2024 Classes and Objects, OOP in C++ 85


Merits and Demerits of Friend Function
Merits Demerits
1. It acts as the bridge 1. It violates the law of data
between two classes by hiding by allowing access to
operating on their private
private members of the class
data’s.
from outside the class.
2. It is able to access
members without need of 2. Breach of data integrity.
inheriting the class. 3. Conceptually messy
3. It can be used to increase 4. Runtime polymorphism in the
the versatility of member cannot be done.
overloading operator.
5. Size of memory occupied by
4. It provides functions that
need data which isn’t objects will be maximum
normally used by the class.
5. Allows sharing private class
information by a non-
member function.

1/25/2024 Classes and Objects, OOP in C++ 86


Sample Program 2.12
Program with Friend function

• Structure:

1/25/2024 Classes and Objects, OOP in C++ 87


Sample Program 2.13:
Create class called One and Two with each having one private member. Add member function to set a value
(say setValue) on each class. Add one more function max() that is friendly to both classes. max() function
should compare two private member of two classes and show maximum among them. Create one-one object
of each class. Then set a value to them. Display the maximum number among them. [PU 2016 Fall, 2015 Fall]

1/25/2024 Classes and Objects, OOP in C++ 88


Friend Class
• A friend class is a technique in OOP, by which a class can access to all data
and function members of another class.
• For e.g, if a class ABC declares another class XYZ as its friend, then XYZ
can access all the data and function members of class ABC.
• Friendship is not mutual. If a class A is friend of B, then B doesn’t become
friend of A automatically.

• Friend class declaration:


class class_name
{
friend class friend_class;// declaring friend class
};

class friend_class
{

};

1/25/2024 Classes and Objects, OOP in C++ 89


Sample program 2.14
Illustration of Friend class

1/25/2024 Classes and Objects, OOP in C++ 90


Sample
program
2.15
Create two
classes One and
Two each has one
private members
and a function
member
getdata(). Make
both the classes
as friend class.
and display both
the data by both
the classes. Make
necessary
functions and
objects as
required to
support your
program.

1/25/2024 Classes and Objects, OOP in C++ 91


Create a class called One and Two with each having a private member. Add member function to set value (say set_value) on each
class Add one more function max() that is friendly to both classes. max() function should compare two private members of two
classes and show maximum among them. Create one object of each class then set a value on them. Display the maximum among
them.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 92
OOP in C++
WAP to add two complex number using concept of constructor.

MESSAGE, INSTANCE AND INITIALIZATION ,


1/25/2024 93
OOP in C++
Sample program 2.16
Write base class that ask the user to enter Time (hour, minute and second) and derived class adds the Time of
its own with the base. Finally make third class that is friend of derived and calculate the difference of base
class time and its own time.

1/25/2024 Classes and Objects, OOP in C++ 94


1/25/2024 Classes and Objects, OOP in C++ 95
1/25/2024 Classes and Objects, OOP in C++ 96
Output:
• Structure:

1/25/2024 Classes and Objects, OOP in C++ 97


Pointer

• A pointer variable in C++ is used to store the


memory address of another variable. Pointers
allow indirect access to variables and enable
dynamic memory allocation and deallocation.
• Declaration: A pointer variable is declared
using the '*' symbol before the variable name.
datatype *pointer_variable;

1/25/2024 Classes and Objects, OOP in C++ 98


Pointer
Initialization:
• Pointers can be initialized with the memory
address of an existing variable using the '&'
operator.
Syntax: datatype variable;
datatype *pointer_variable =
&variable;
Accessing Value:
• To access the value of the variable that a
pointer is pointing to, the pointer needs to be
dereferenced using the '*' operator.
Syntax: *pointer_variable;
1/25/2024 Classes and Objects, OOP in C++ 99
Reference Variable
• A reference variable is an alias, that is, another
name for an already existing variable.
• Once a reference is initialized with a variable,
either the variable name or the reference name
may be used to refer to the variable.
• When a variable is declared as a reference, it
becomes an alternative name for an existing
variable.
• A variable can be declared as a reference by putting
‘&’ in the declaration.
• A reference variable must be initialized at the time
of declaration.

1/25/2024 Classes and Objects, OOP in C++ 100


Reference Variable
• Declaration

• Where:
– regular_variable is a variable that has already initialized,
– reference_variable is an alternative name (alias) to
represent the variable regular_variable

1/25/2024 Classes and Objects, OOP in C++ 101


Sample program
Illustration of Reference variable

1/25/2024 Classes and Objects, OOP in C++ 102


Default Arguments
• A default argument is a value provided in a function declaration that is
automatically assigned by the compiler if the caller of the function doesn’t provide
a value for the argument with a default value.
• We can specify default values i.e. some fixed values for arguments in function so
that when such function is called without specifying all its arguments, the C++
function assigns the default value to the parameter which does not have a
matching argument in the function call.
• If the function is called with explicit value for default argument, the supplied value
is used for that argument.
• But when the value is not passed for the default argument, the default value is
used for that argument.
• Thus, defining default argument means like making optional argument. The default
values are specified in function prototypes.

1/25/2024 Classes and Objects, OOP in C++ 103


Default Arguments
• Syntax:

1/25/2024 Classes and Objects, OOP in C++ 104


Sample program
Illustration of default arguments.

1/25/2024 Classes and Objects, OOP in C++ 105


End of chapter

1/25/2024 Classes and Objects, OOP in C++ 106

You might also like