You are on page 1of 125

UNIT III CLASSES AND OBJECTS

Concepts of Object Oriented Programming – Benefits of


OOP – Simple C++ program - Classes and Objects -
Member functions - Nesting of member functions -
Private member functions - Memory Allocation for
Objects - Static Data Members - Static Member functions
- Array of Objects - Objects as function arguments -
Returning objects - friend functions – Const Member
functions - Constructors – Destructors
Difference between C and C++
S.
No. C C++
Developed by Dennis Ritchie at
Developed by Bjarne Stroustrup at
AT&T Bell Labs between 1969 and
Bell Labs starting in 1979.
1 1973.
Originally developed from the C
Free-format program source code
2 programming language
C++ is a superset of C. C++ can
C is a subset of C++. It cannot run
run most of C code while C cannot
C++ code.
3 run C++ code.
4 Functions Objects
Contains 32 Keywords Contains 52 Keywords
Uses calloc(), malloc() and free()
Uses operators new and delete for
functions for allocating and de-
the same purpose.
5 allocating memory.

C is a structural or procedural C++ is an object oriented


6 programming language. programming language.
Data is hidden and can’t be accessed
In C, the data is not secured. by external functions.

C follows top down approach. C++ follows bottom up approach

C uses scanf() and printf() function C++ uses cin>> and cout<< for
for standard input and output. standard input and output.
Variables must be defined at the
beginning in the function. Modern C
compilers such as gcc support the
C99 and C11 standards, which allow Variables can be defined anywhere
you to declare a variable anywhere. in the function.
In C++, namespace feature is
In C, namespace feature is absent. present.
C is a middle level language. C++ is a high level language.

Programs are divided into modules Programs are divided into classes
and functions. and functions.
C doesn’t support exception C++ supports exception
handling directly. Can be done handling. Done by using try
by using some other functions. and catch block.
Features like function C++ supports function
overloading and operator overloading and operator
overloading is not present. overloading.
C uses functions for C++ uses objects for input
input/output. output.
For example scanf and printf. For example cin and cout.
C has no support for virtual C++ supports virtual and
and friend functions. friend functions.
Software Evaluation

The software evolution has had distinct phases “layers” of growth.


These layers were building up one by one over the last five decades
. Each layer representing and improvement over the previous one.
In software system each of the layers continues to be functional,
whereas in the case of trees, only the uppermost layer is functional.
1, 0

Machine Language

Assembly Language

Procedure- Oriented

Object Oriented Programming


Procedure-Oriented Programming
In the procedure oriented approach, the problem is viewed as the
sequence of things to be done such as reading, calculating and
printing such as Cobol, Fortran and c. The primary focus is on
functions. A typical structure for procedural programming is
shown in fig.1.2. The technique of hierarchical decomposition
has been used to specify the tasks to be completed for solving a
problem.
Main Program

Function-1 Function-2 Function-3

Function-4
Function-5

Function-6 Function-7 Function-8

Fig. 1.2 Typical structure of procedural oriented programs


It ties data more closely to the function that operate on it, and
protects it from accidental modification from outside function.
OOP allows decomposition of a problem into a number of
entities called objects and then builds data and function around
these objects.
The data of an object can be accessed only by the function
associated with that object. However, function of one object can
access the function of other objects.
Organization of data and function in OOP
Object A O bject B

DATA DATA
Communication

FUNCTION FU N C T IO N

Object c
DATA

FU N C T IO N
Basic Concepts of Object Oriented Programming

•Objects
•Classes
•Data abstraction
•Encapsulation
•Inheritance
•Polymorphism
•Dynamic binding
•Message passing
Objects
Objects are the basic run time entities in an object- oriented
system. They may represent a person, a place, a bank account, a
table of data or any item that the program has to handle. They
may also represent user-defined data such as vectors, time and
lists.

When a program is executed, the objects interact by sending


messages to one another. Foe example, if “customer” and
“account” are to object in a program, then the customer object
may send a message to the count object requesting for the bank
balance. Each object contain data, and code to manipulate data.
OBJECTS: STUDENT

DATA
Name
Date-of-birth
Marks

FUNCTIONS
Total
Average
Display
………

Fig. 1.5 representing an object


Classes

The entire set of data and code of an object can be made a user -defined
data type with the help of class. In fact, objects are variables of the type
class. Each object is associated with the data of type class with which they
are created.

A class is thus a collection of objects similar types. For examples, Mango,


Apple and orange members of class fruit. Classes are user-defined that
types and behave like the built-in types of a programming language.

Once a class has been defined, we can create any number of objects
belonging to that class.

Fruit Mango;

Will create an object mango belonging to the class fruit.


Data Abstraction and Encapsulation

The wrapping up of data and function into a single unit (called


class) is known as encapsulation. Data and encapsulation is the
most striking feature of a class. The data is not accessible to the
outside world, and only those functions which are wrapped in the
class can access it. These functions provide the interface between
the object’s data and the program. This insulation of the data from
direct access by the program is called data hiding or information
hiding.
1. We can not access any function from the class directly. We need an
object to access that function that is using the member variables of that
class.
2.The function which we are making inside the class must use only
member variables, only then it is called encapsulation.
Abstraction refers to the act of representing essential features
without including the background details or explanation. Classes
use the concept of abstraction and are defined as a list of abstract
attributes such as size, wait, and cost, and function operate on
these attributes. They encapsulate all the essential properties of the
object that are to be created.
The attributes are some time called data members because
they hold information. The functions that operate on these
data are sometimes called methods or member function.
Inheritance

Inheritance is the process by which objects of one class


acquired the properties of objects of another classes. It
supports the concept of hierarchical classification.

For example, the bird, ‘robin’ is a part of class ‘flying


bird’ which is again a part of the class ‘bird’. The principal
behind this sort of division is that each derived class
shares common characteristics with the class from which
it is derived as illustrated in fig 1.6.

In OOP, the concept of inheritance provides the idea of


reusability. This means that we can add additional features
to an existing class without modifying it. This is possible
by deriving a new class from the existing one. The new
class will have the combined feature of both the classes.
Fig. 1.6 Property inheritances

BRD

Attributes

Features

Lay Eggs

F ly in g B ird Non Flying Bird

Attributes Attributes
………… ………..
………... ………..

Robin Swallow Penguin Kiwi


Attributes Attributes Attributes Attributes
………… ………… ………… …………
… … … ... ………... ………... ………...
Polymorphism
Polymorphism is another important OOP concept.
Polymorphism, a Greek term, means the ability to take more than
on form.
The word “polymorphism” means having many forms.
In simple words, an ability can take more than one form.
The process of making an operator to exhibit different behaviors
in different instances is known as operator overloading.

Using a single function name to perform different type of task is


known as function overloading.
Shape

Draw

Circle Object Box object Triangle Object

Draw (Circle) Draw (box) Draw (triangle)

Fig. 1.7 Polymorphism


Dynamic Binding
Binding refers to the linking of a procedure call to the code to be
executed in response to the call.
Consider the procedure “draw” in fig. 1.7. by inheritance, every
object will have this procedure. Its algorithm is, however, unique
to each object and so the draw procedure will be redefined in each
class that defines the object. At run-time, the code matching the
object under current reference will be called.
Message Passing
An object-oriented program consists of a set of objects that
communicate with each other.
1.Creating classes that define object and their behavior,
2.Creating objects from class definitions, and
3.Establishing communication among objects.
Objects communicate with one another by sending and receiving
information much the same way as people pass messages to one
another. The concept of message passing makes it easier to talk
about building systems that directly model or simulate their real-
world counterparts.
A Message for an object is a request for execution of a procedure,
and therefore will invoke a function (procedure) in the receiving
object that generates the desired results. Message passing involves
specifying the name of object, the name of the function (message)
and the information to be sent
Example:

Employee. Salary (name);

Object
Information
Message
Application of OOP

Hundreds of windowing systems have been developed, using


the OOP techniques.

•Real-time system
•Simulation and modeling
•Object-oriented data bases
•Hypertext, Hypermedia, and expertext
•AI and expert systems
•Neural networks and parallel programming
•Decision support and office automation systems
•CIM/CAM/CAD systems
//PRINT NUMBER ENTERED BY USER

#include<iostream>
using namespace std;
int main()
{
int number;
cout<<“Enter an integer: ”;
cin>> number;
cout<<“You entered: ” << number;
return 0;
}

OUTPUT
Enter an integer: 23
You entered: 23
//PROGRAM TO FIND QUOTIENT AND REMAINDER
#include<iostream>
using namespace std;
int main()
{
int divisor, dividend, quotient,remainder;
cout<< “Enter dividend: ”;
cin>> dividend;
cout<< “Enter divisor: ”;
cin>> divisor;
quotient = dividend / divisor;
remainder = dividend % divisor;
cout<< “Quotient= “ << quotient << endl;
cout<< “Remainder= “<<remainder;
return 0;
}
OUTPUT
Enter dividend: 13
Enter divisor: 4
Quotient = 3
Remainder = 1
//Program to check palindrome number
#include<iostream>
using namespace std;
int main()
{
int n, num, digit, rev=0;
cin>> num;
n=num;
while(n>0)
{
digit = num%10;
rev=(rev*10)+digit;
num = num/10;
}
if(n==rev)
cout<<“The number is a palindrome.”;
else
cout<<“The number is not a palindrome.”;
return 0
}
Output
Enter the positive number: 12321
The reverse of the number is: 12321
The number is a palindrome
//PROGRAM TO CHECK PRIME NUMBER
#include<iostream>
using namespace std;
int main()
{
int num, i;
cin>>num;
for (i=2;i<=num-1;i++)
{
if (num%i==0)
{
cout<<"The number is not a prime number";
break;
}
}
if (i== num)
cout<<"The number is a prime number";
return 0;
}
Output

5
The number is a prime number
6
The number is not a prime numbe
//PROGRAM TO DISPLAY ALL FACTORS OF A NUMBER
#include<iostream>
using namespace std;
int main()
{
int n, i;
cin>>n;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
cout<<i<<“ “;
}
}
return 0;
}
Output
60
1 2 3 4 5 6 10 12 15 20 30 60
//PROGRAM TO CHECK VOWEL OR A CONSONANT MANUALLY
#include<iostream>
using namespace std;
int main()
{
char c;
bool islower, isupper;
cin>>c;
islower=(c==‘a’ || c==‘e’ || c==‘I’ || c==‘o’ || c==‘u’);
isupper=(c==‘A’ || c==‘E’ || c==‘I’ || c==‘O’ ||c==‘U’);
if(!isalpha(c))
cout<<“Not a alphabet”;
else
if(islower || isupper)
cout<< c<<“is a vowel”;
else
cout<<c<<“is a consonant.”;
return 0;
}

Output
Enter an alphabet: u
u is a vowel
DEFINING A CLASS

1.A Class is defined using keyword class followed by the name of


the class.

2.The body of the class is defined inside the curly brackets and
terminated by the semicolon at the end.
EXAMPLE

class Car
{
Public:
string brand;
string model;
int year;
};
An Object is an instance of a class.

•Objects are the basic run-time entities in an object-oriented system.


•They may represent a person, a place, a bank account, a table of data or
any item that the program has to handle.
•Objects take up space in the memory and have an associated address like
a record in Pascal or a structure in C.
•When a program is executed, the objects interact by sending messages to
one another.

For example, if “customer” and “account” are two objects in a program,


then the customer object may send a message to the account object
requesting for the bank balance.
Declaring Object

When Class is defined no memory is allocated but when it is


instantiated memory is allocated.
The object is created to uses the data and access functions defined in
the class.

SYNTAX

ClassName ObjectName;
EXAMPLE
#include<iostream.h>
class Car
{
Public:
string brand;
string model;
int year;
};
int main()
{
Car obj1; // Creating an object of class car
obj1.brand = “BMW”;
obj1.model = “X5”;
obj1.year = 1999;
cout << obj1.brand << ” “ << obj1.model << “ “ << obj1.year;
}
O/P
BMW X5 1999
Data Members and Member Functions

Data members are the data variables and member functions are the
functions used to manipulate these variables and together defines the
properties and behavior of the objects in the class.

For example

Car is the class, the speed limit, mileage are the data members and apply
brakes, increase speed are the member functions.
Example
#include<iostream.h>
class Car
{
public:
int speed_limit, mileage; //Data member
void apply_break() // Member function
{
cout<< “Applybreak” ;
}
void increase_speed() // Member function
{
cout<< “Increase speed” ;
}
}
int main()
{
Car obj1; // Creating object for the class
Obj1.apply_break(); // Accessing member function
Obj1.increase_speed(); // Accessing member function
}

Output
Apply break
Increase speed
Accessing Data Member and Member Functions

1.The data members and member functions of class can be accessed


using dot (.) operator with the object.

2.The public data members can be accessed directly by the object


whereas the private data member cannot be accessed directly by the
object.

3.Accessing data members depends on the access control of that data


members.
Example
#include<iostream.h>
class Car
{
public:
string model //Data member
void printcarmodel() // Member function
{
cout<< “ Car model name is ” <<obj.model;
}
}
int main()
{
Car obj1; // Creating object for the class
obj1.model = “BMW X5”; // Accessing data member
obj1.printcarmodel(); // Accessing member function
}

O/P
Car model name is BMW X5
Defining Member Functions in Classes

Member functions can be defined in two places:


i) Outside the class definition
ii) Inside the class definition

i)Outside The Class Definition

To define a function outside the class definition, it can be declared inside


the class and define outside of the class.

It can be performed by specifiying the name of the class, followed the


scope resolution operator(::), followed by the name of the function.
Example
#include<iostream.h>
class Cars
{
public:
void printname();
};
void Cars:: printname()
{
cout << “I am BMW”;
}
int main()
{
Cars obj1;
obj1.printname();
}

Output
I am BMW
ii) Inside The Class Definition
Another method of defining a member function is to replace the function
declaration by the actual function definition inside the class.
Example
#include<iostream.h>
class Cars
{
public:
void printname()
cout << “I am BMW”;
};
int main()
{
Cars obj1;
obj1.printname();
}

OUTPUT
I am BMW
Nesting of Member Function

A member function can be called by using its name inside another


member function of the same class. This is known as nesting of member
function.

EXAMPLE

#include<iostream.h>
class set
{
int m, n;
public:
void input(void):
void display(void);
int largest(void);
};
int set :: largest(void)
{
if(m>=n)
return (m);
else
return(n);
}
void set :: input(void)
{
cout << “Input values of m and n” << “\n”;
cin >> m >> n;
}
void set :: display(void)
{
cout<< “Largest value =” << largest() << “\n”;
}
int main()
{
set A;
A.input();
A.display();
return 0;
}

Output
Input values of m and n
23 13
Largest value = 23
Private Member Function

•A function declared inside the private access specifier of the class is


known as a private member function.
•A private member function can be accessed through the only public
member function of the same class.

Example
For example, there is a class named “student” which has the
following
private data members and public member functions:
#include <iostream>
using namespace std;
class Student
{
private:
int rNo;
float percentage;
void TakeNumbersBegin(void) //private member functions
{
cout<<"Input start..."<<endl;
}
void TakeNumbersBeginFinish(void)
{
cout<<"Input end..."<<endl;
}
public:
void read(void) //public member functions
{
TakeNumbersBegin(); //calling first member function
cout<<“Enter roll number”;
cin>>rNo;
cout<<“Enter percentage”;
cin>>percentage;
TakeNumbersBeginFinish(); //calling second member function
}
void print(void)
{
cout<<endl;
cout<<"Roll Number: "<<rNo<<endl;
cout<<"Percentage: "<<percentage<<"%"<<endl;
}
};
int main()
{
Student object1;
object1.read();
object1.print();
return 0;
}
Private Data Members
rNo is used to store the roll number of the student.
perc is used to store the percentage of the student.

Public Member Functions


read() – read() function is used to read roll number and percentage of the
student.
print() – print() function is used to print roll number and percentage of the
student.

Here, TakeNumberBegin() and TakeNumberBeginFinish() are the private


member functions which are calling inside public member function in the
same class.
Memory Allocation for Object
Before using a member of a class, it is necessary to allocate the required
memory space to that member.
The way the memory space for data members and member functions is
allocated is different regardless of the fact that both data members and
member functions belong to the same class.
The memory space is allocated to the data members of a class only when an
object of the class is declared, and not when the data members are declared
inside the class.
Since a single data member can have different values for different objects at
the same time, every object declared for the class has an individual copy of
all the data members.
On the other hand, the memory space for the member functions is allocated
only once when the class is defined.
In other words, there is only a single copy of each member function, which is
shared among all the objects.
For instance, the three objects, namely, book1, book2 and book3 of the class
book have individual copies of the data members title and price.
However, there is only one copy of the member functions getdata ()
and putdata () that is shared by all the three objects.
Static Data Members

1.Static data members are class members that are declared using the static
keyword.
2.There is only one copy of the static data member in the class, even if there
are many class objects.
3.This is because all the objects share the static data member.
4.The static data member is always initialized to zero when the first class
object is created.
Syntax:

static data_type data_member_name;

In the above syntax, static keyword is used. The data_type is the C++
data type such as int, float etc.

The data_member_name is the name provided to the data member.


Example:

#include <iostream>
#include<string.h>
using namespace std;
class Student
{
private:
int rollNo;
char name[10];
int marks;
public:
static int objectCount;
Student()
{
objectCount++;
}
void getdata()
{
cout << "Enter roll number: "<<endl;
cin >> rollNo;
cout << "Enter name: "<<endl;
cin >> name;
cout << "Enter marks: "<<endl;
cin >> marks;
}
void putdata()
{
cout<<"Roll Number = "<< rollNo
<<endl;
cout<<"Name = "<< name <<endl;
cout<<"Marks = "<< marks <<endl;
cout<<endl;
}
};
int Student::objectCount = 0;
int main(void)
{
Student s1;
s1.getdata();
s1.putdata();
Student s2;
s2.getdata();
s2.putdata();
Student s3;
s3.getdata();
s3.putdata();
cout << "Total objects created = “ << Student::objectCount;
return 0;
}
OUTPUT:
Enter roll number: 1
Enter name: Mark
Enter marks: 78
Roll Number = 1
Name = Mark
Marks = 78
Enter roll number: 2
Enter name: Nancy
Enter marks: 55
Roll Number = 2
Name = Nancy
Marks = 55
Enter roll number: 3
Enter name: Susan
Enter marks: 90
Roll Number = 3
Name = Susan
Marks = 90
Total objects created = 3
Static Member Function

The static member functions are special functions used to access the static
data members or other static member functions.

A member function is defined using the static keyword.


A static member function shares the single copy of the member function
to any number of the class objects.

We can access the static member function using the class name or class
objects.
If the static member function accesses any non-static data member or non-
static member function, it throws an error.

SYNTAX:
class_name::function_name(parameter);
EXAMPLE:
//create program to access the static member function using the class name

#include <iostream>
using namespace std;
Class Note
{
static int num; //Declare a static data member
public:
static int fun() // Create static member function
{
return num;
}
};
int Note :: num =5; /*Initialize the static data member using the class name and the scope resolution operator*/

int main()
{
cout<<“The value of the num is: “<<Note :: func() <<endl; /*Access static member
function using the class name and scope resolution operator*/

return 0;
}

Output:
The value of the num is: 5
Arrays of Objects

We know that an array can be of any data type including struct.


Similarly, we can also have arrays of variables that are of the type class.
Such variables are called arrays of objects.

Consider the following class definition:

class employee
{
char name[30];
int id;
public:
void getdata(void);
void putdata(void);
};
employee manager[3];
employee foreman[15];
employee worker[75];

The array manager contains three objects (manager[0],


manager[1],manager[2]) of type employee class.
Similarly, the foreman array contains 15 objects and the worker
array contains 75 objects.
Since an array of objects behaves like any other array, we can use
the usual array-accessing methods to access individual elements,
and then the dot member operator to access the member functions.
manager[i].putdata();

The above statement will display the data of the ith element of the array
manager. That is, this statement requests the object manager[i] to invoke
the member function putdata().
An array of objects is stored inside the memory in the same way as a
multi-dimensional array.
Member functions are stored separately and will be used by all the
objects.
Example:
#include<iostream>
using namespace std;
class employee
{
char name[30];
float age;
public:
void getdata(void);
void putdata(void);
};
void employee :: getdata(void)
{
cout<< “Enter name: ”;
cin>> name;
cout<< “Enter age: ”;
cin>>age;
}
void employee :: putdata(void)
{
cout<< “Name: ”<< name << “\n”;
cout<< “Age: ”<< age << “\n”;
}
const int size = 3;
int main()
{
employee manager[size];
for(int i=0; i<size; i++)
{
cout << “\nDetails of manager” << i+1 << “\n”;
manager[i].getdata();
}
for(i=0; i<size; i++)
{
cout<< “\nManager” << i+1 << “\n”;
manager[i].putdata();
}
return 0;
}
Output:
Details of manager1
Enter name: Geetha
Enter age: 45
Details of manager2
Enter name: Arun
Enter age: 37
Details of manager3
Enter name: Sam
Enter age: 50
Manager1
Name: Geetha
Age: 45
Manager2
Name: Arun
Age: 37
Manager3
Name: Sam
Age: 50
Object as Function Argument

1. The objects of a class can be passed as arguments to member


functions as well as non member functions either by value or by reference.
When an object is passed by value, a copy of the actual object is created
inside the function.
2. This copy is destroyed when the function terminates. Moreover, any
changes made to the copy of the object inside the function are not reflected
in the actual object.
3. On the other hand, in pass by reference, only a reference to that
object (not the entire object) is passed to the function. Thus, the changes
made to the object within the function are also reflected in the actual object.
4. Whenever an object of a class is passed to a member function of the
same class, its data members can be accessed inside the function using the
object name and the dot operator.
However, the data members of the calling object can be directly accessed
inside the function without using the object name and the dot operator.
Example:
#include<iostream.h>
class weight
{
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
};
void weight :: getdata()
{
cout<<“Kilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
void weight :: putdata ()
{
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
}
void weight :: sum_weight(weight w1,weight w2)
{
gram = w1.gram + w2.gram;
kilogram=gram/1000;
gram=gram%1000;
kilogram+=w1.kilogram+w2.kilogram;
}
int main ()
{
weight w1,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
w1.getdata();
cout<<" \n Enter weight #2" ;
w2.getdata();
w3.sum_weight(wl,w2);
cout<<"/n Weight #1 = ";
w1.putdata();
cout<<"Weight #2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();
return 0;
}
Output:

Enter weight in kilograms and grams


Enter weight #1
Kilograms: 12
Grams: 560
Enter weight #2
Kilograms: 24
Grams: 850
Weight #1 = 12 Kgs. and 560 gms.
Weight #2 = 24 Kgs. and 850 gms.
Total Weight = 37 Kgs. and 410 gms.
In this example, the sum_weight() function has direct access to the data
members of calling object (w3 in this case).

However, the members of the objects passed as arguments (w1 and w2)
can be accessed within function using the object name and dot operator.

Note that, the objects w1 and w2 are passed by value, however, they
can re passed by reference also.

For example, to pass w1 and w2 by reference to the function


sum_weight the function will be declared and defined as void
sum_weight (weight &,weight &) ;
void weight :: sum_weight (weight & w1, weight & w2)
{
// body of function
}
Returning Object
An object is an instance of a class. Memory is only allocated when an
object is created and not when a class is defined. An object can be returned
by a function using the return keyword.
#include<iostrem>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1 = 0, int y1 = 0)
{
x=x1; y=y1;
}
Point addPoint(Point P)
{
Point temp; temp.x = x+p.x; temp.y = y+p.y;
return temp;
}
void display()
{
cout<< “x = ” << x << “ ”;
cout<< “y = ” << y << “ ”;
}
};
int main()
{
Point p1(5,3);
Point p2(12,6);
Point p3;
cout<< “Point1”;
p1.display();
cout<< “Point2”;
p2.display();
p3=p1.adpoint(p2);
cout<< “The Sum of the two points: ”;
p3.display();
return 0;
}
Output:

Point1
x=5
y=3

Point2
x=12
y=6

The Sum of the two points:


x=17
y=9
FRIEND FUNCTIONS

1.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.
2.Even though the prototypes for friend functions appear in the class
definition, friends are not member functions.
3.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.
4.To declare a function as a friend of a class, precede the function
prototype in the class definition with keyword friend.
Example:
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.
Example:
#include<iostream>
using namespace std;
class Box
{
double width:
public:
friend void printWidth(Box box);
void setWidth(double wid);
};
void Box :: setWidth(double wid) //Member function definition
{
width = wid;
//printwidth() is a friend of Box
}
void printWidth(Box box)
{
cout<<”Width of box: “<<box.width<<endl;
}
int main()
{
Box box;
box.setWidth(10.0);
return 0;
}

Output
Width of box: 10
Const Member Function

 The const member functions are the functions which are declared as
constant in the program. The object called by these functions cannot be
modified.

 It is recommended to use const keyword so that accidental changes to


object are avoided.

 A const member function can be called by any type of object.

 Non-const functions can be called by non-const objects only.


Syntax:

i) For function decleration within a class


<return type> <function name> () const

ii)For function definition within the class decleration


<return type> <function name> () const
{
//Body of the function
}

iii)For function definition outside the class


<return type> <class name> :: <function name>() const
{
//Body of the function
}
Example:

#include<iostream>
using namespace std;
class Demo
{
int val;
public:
Demo(int x =0)
{
val = x;
}
int getvalue() const
{
return val;
}
};
int main()
{
const Demo d(28);
Demo d1(8);
cout<< “The value using object d: ” << d.getvalue();
cout<< “The value using object d1: ”<< d1.getvalue();
return 0;
}

Output
The value using object d: 28
The value using object d1: 8
CONSTRUCTOR
•It is a special method that is invoked automatically at the time of object
creation.
•It is used to initialize the data members of new objects.
•The constructor has the same name as the class or structure.
•Constructor is invoked at the time of object creation.
•Constructor does not have a return value, hence they do not have a return
type.

Syntax for constructor

<classname> (list of parameters);


Constructor can be defined inside or outside the class declaration.

Syntax for defining the constructor within the class


<classname> (list of parameters)
{
//constructor definition
}
Example
#include<iostream>
using namespace std;
class student
{
int rno;
char name[10];
double fee;
public:
student()
{
cout << “Enter the RollNo: ”;
cin>>rno;
cout << “Enter the Name: “;
cin>>name;
cout << “Enter the fee: ”;
cin<<fee;
}
void display()
{
cout << endl << rno << “\t” << name << “\t” <<fee;
}
};

int main()
{
student s;
s.display();
return 0;
}

Output:
Enter the RollNo: 101
Enter the Name: Guru
Enter the Fee: 190000
101 Guru 190000
Syntax for defining the constructor outside the class
<classname> :: <classname> (list of parameter)
{
//constructor definition
}

Example
#include<iostream>
using namespace std;
class student
{
int rno;
char name[10];
double fee;
public:
student();
void display();
};
student :: student()
{
cout << “Enter the RollNo: ”;
cin>>rno;
cout << “Enter the Name: “;
cin>>name;
cout << “Enter the fee: ”;
cin<<fee;
}
void student::display()
{
cout<< endl << rno << “\t” <<name << “\t” << fee;
}
int main()
{
student s;
s.display();
return 0;
}
Output:

Enter the RollNo: 102


Enter the Name: Ram
Enter the Fee: 70000

102 Ram 70000


Characteristics of constructor

 The name of the constructor is the same as its class name.


 Constructor are mostly declared in the public section of the class though
it can be declared in the private section of the class
 Constructor do not return values. Hence they do not have a return type.
 A constructor gets called automatically when we create the object of the
class.
 Constructor can be overloaded.
 Constructor cannot be declared virtual.
TYPES OF CONSTRUCTOR
1.Default Constructor
2.Parameterized Constructor
3.Copy Constructor
Default Constructor
 Default constructor do not take any parameters. If a default
constructor is not provided by the programmer explicitly, then the
compiler provides a implicit default constructor.
 The default values of the variables are 0.
 If we do not define any constructor explicitly, the compiler will
automatically provide a default constructor implicitly
Example
#include<iostream>
using namespace std:
class construct
{
public:
int a, b;
construct()
{
a=10;
b=20;
}
};
int main()
{
construct c;
Output:
cout<< “a: ”<< c.a<<endl<<“b: ”<<c.b;
return 1; a: 10
} b: 20
Parameterized Constructor
 The parameterized constructors can take arguments to initialize an object
when it is created.
 Parameters are added to a parameterized constructor just like they are
added to a normal function.
 When object is declared in a parameterized constructor, the initial values
have to be passed as arguments to the constructor function.
 The parameterized constructors can be called implicitly or explicitly.
USE OF PARAMETERIZED CONSRTUCTOR

 It is used to initialize the various data element of different objects with


different values when they are created.
 It is used to overload constructors.
Output
num1 = 3
num2 = 8
COPY CONSTRUCTOR

 A copy constructor is a member function that initializes an object using


another object of the same class.
 A constructor which creates an object by initializing it with an object of
the same class, which has been created previously is known as a copy
constructor.

SYNTAX
ClassName(const ClassName &old_obj);
Example:
#include<iostream.h>
#include<string.h>
using namespace std;
class student
{
int rno;
string name;
double fee;
public:
student(int,string,double);
student(student &t)
{
rno = t.rno;
name = t.name;
fee = t.fee;
}
void display();
};
student ::student(int no,string n, double f)
{
rno = no;
name = n;
fee = f;
}
void student :: display()
{
cout<<endl<<rno<< “\t”<<name<< “\t”<<fee;
}
int main()
{
student s(1001, “sam”, 10000);
s.display();
student sam(s);
sam.display();
Output
return 0;
} 1001 Sam 10000
1001 Sam 10000
Destructor

•A destructor is a special member function of a class that is executed


whenever an object of its class goes out of scope or whenever the delete
expression is applied to a pointer to the object of that class.

•A destructor will have exact same name as the class prefixed with a
tilde(~) and it can neither return a value nor can it take any parameters.

•Destructor can be very useful for releasing resources before coming out of
the program like closing files, releasing memories.
Example

#include<iostream>
Using namespace std;
class Line
{
public:
void setLength(double len);
double getLength(void);
Line(); //This is the constructor decleration
~Line(); // This is the destrutor decleration
private:
double length;
};
Line :: Line(void)
{
cout<<“Object is being created”<<endl;
}
Line :: ~Line(void)
{
cout<<“Object is being deleted”<<endl;
}
void Line :: setLength(double len)
{
length = len;
}
double Line :: getLength(void)
{
return length;
}
int main()
{
Line line;
line.setLength(6.0);
cout<<“Length of Line: “<<line.getLength()<<endl;
return 0;
}
Output
Object is being created
Length of line: 6
Object is being deleted
THANK YOU

You might also like