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

Final UNIT-2 - C++

Uploaded by

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

Final UNIT-2 - C++

Uploaded by

rajasuriaa51
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/ 24

SREE NARAYANA GURU COLLEGE, KG CHAVADI

BSc CS, IT, CT, SS, CSA, MM & B.C.A (Regular) –II SEMESTER
CORE 3: C++ PROGRAMMING
UNIT-2
Staff Name: S. Ganeshmoorthy MCA., M.Phil., MBA (Ph.D.)
-----------------------------------------------------------------------------------------------------------------------------------------
UNIT II: Classes and Objects: Declaring Objects – Defining Member Functions – Static Member
variables and functions – array of objects –friend functions – Overloading member functions – Bit
fields and classes – Constructor and destructor with static members.
------------------------------------------------------------------------------------------------------------------------------
Classes and Objects
Synopsis
1. Introduction
2. Definition of class
3. Class declaration
4. Explanation about class declaration
5. Members
6. Data Members
7. Encapsulation
8. Example program for class
9. Representation of Class
10. Access specifier in a class
 Public
 Private
 Protected
Introduction
 The important feature of C++ is “class”.
 A class is a user defined data type to implement an abstract object
 Abstract means to hide the details
 A class is a combination of data and functions
 Data is called data members and function are called as member functions
 A class is an extension of the idea of structure used in C.
 It is a new way of creating and implementing a user defined data type.

Definition of class:

“A class is grouping of objects having identical properties, common behavior & shared relationship.”

Specifying a Class
 A Class is a way to bind(fix) the data and its associated function together
 It allows the data and function to be hidden from external use.
 A group of object is called class
 Object is real world run time entity
 It may be any living or non living things
 It consist of attributes and methods
 Attributes=> characteristics or behaviour
 Methods=> Fuctionality

1
Class declaration

Class classname
{
Private:
Variable declarations;
Private section
Function declarations;
(members)
Public: Access specifier
Variable declarations;
Function declarations; Public section
}; (members)

Explanation about class declaration

In above syntax the class declaration


 Class => it is a keyword that specifies abstract data of type class name
 Body of class => it is enlcosed within braces [{ }] and terminated by semicolon[;]
 Declarations=> the body of class contains the declaration of variables and funcions which is
said to be members

Example program for class


Class item
{
Int number; // member variables
Float cost; // member variables
Public:
Void getdata(int a, float b); // member function
Void putdata(void); // member function
};

 In the above example


 The class declaration is enclosed with curly braces ({}) and terminated by a semicolon (;).
 The variables inside the class is termed as member variables and
 The functions are termed as member function
 The member variables and member functions are divided into 2 sections
 i.e., private and public.
 The private and public keywords are terminated by colon (:)

Representation of Class

2
Members
 Members => The collection of functions and variables are said to be members
 The members are denoted as two ways
 Private
 Public

Data members
 The variables declared inside the class are known as data members
 The functions are known as member functions
 Only member functions can have access to private data members and private function

Encapsulation
 The binding or wrapping or packaging or covering of data and functions together into a single
class type variable is referred to as encapsulation

Data Hiding in class

Access specifier in a class:


 There are 3 access specifiers that are used in a class.
1. Public
2. Private
3. Protected

Public Keyword:
 The member variables and the member functions declared in the public section can be
directly accessed with the help of object.
 Public keyword is terminated by a colon (:)

Private Keyword:

3
 The member variables and the member functions declared in the Private section cannot be
directly accessed with the help of object.
 The private keyword is used to prevent direct access of member variables and functions.
 Private keyword is terminated by a colon (:)

Protected Keyword:
 The protected keyword has the same effect as the private.
 The protected keyword is used in the inheritance of classes.
 Protected keyword is terminated by a colon (:)

Declaring objects

Synopsis
1. Introduction
2. Definition of class
3. State identity and behavior of objects
4. Syntax for creating object
5. Example for creating object
6. Accessing class Members
7. Formats for calling a member function
8. Example
Introductin
 Once a class (ITEM) has been created , we can create variable of that type (class type) by using
following syntax which is called object

Definition of Object
 Object is real world run time entity
 Entity is an real world object
 It may be any living or non living things
 It consist of attributes and methods
 Attributes=> characteristics or behaviour
 Methods=> Fuctionality
 An object is an instance of a class.
 An object is a class variable.
 Is can be uniquely identified by its name.
 Every object has a state which is represented by the values of its attributes.
 These state are changed by function which applied on the object

State identity and behavior of objects


 Every object has identity, behavior and state.
 The identity of object is defined by its name, every object is unique and can be differentiated
from other objects.
 The behavior of an object is represented by the functions which are defined in the object’s class.
These functions show the set of action for every objects.
 The state of objects are referred by the data stored within the object at any time moment.

Syntax for creating object

Class Classname
{
…….
}object name
4
Or

Class_name Object_name

Example for creating object

Class Student
{
…..
}s1,s2;

Or
Student s1;

 In c++, the class variables are known as objects


 For eg
o Item x;
 In the above example, x is called an object of type item
 We may also declare more than one object in one statement
 For eg
o Item x, y, z;
 Declaration of an object is similar to the variable of any data type
 The objects are the real world entities
 Objects can be created when class is defined by placing their names immediately after the
closing brace.
 For eg
Class item
{

} x,y,z;

 The object can access only the public member variables and member functions of a class by
using operator dot (.) and arrow (->)
 The syntax is as follows,

[object_name] [operator] [member_name];


 Ex: ”one‟ is a normal object so it is used with a dot operator.
o one.show( );
 Ex: If “one‟ is a pointer object then it is used with arrow operator.
o one->show( );

Accessing class Members

 The private data of a class can be accessed only through the member functions of that class.
 The main ( ) cannot contain statements that access number and cost directly.

Formats for calling a member function

Object-name.function-name (actual arguments);

Example:
5
x.getdata(100, 75.5);

 In the above example the value 100 is the number and 75.5 is the cost of an object x by
implementing getdata( ) function.
 Similarly, the statement
X.putdata( );

 In above function it send a message to the object x requesting to display its contents
 A variable declared as public can be accessed by objects directly

Class xyz
{
Int x;
Int y;
Public
Int z;
};
….
….
Xyz p;
p.x=0; //error, x is private
p.z=10 //OK, z is pubic
….
….

Defining Member functions

Synopsis
1. Introduction
a. Inside the class definition
b. Outside the class definition
2. Private member function

Introduction
 A member function can be defined in two places in the class
 It can be defined in 2 places
o Inside the class definition
o Outside the class definition

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
 For eg we define the item class as follows

Class item
{
Int number;
Float cost;
Public:
Void getdata(int a, float b); //declaration
//inline function
Void putdata (void); //definition

6
{
Cout <<number<<”\n”;
Cout<<cost<<”\n”;
}
};
 When a function is defined inside a class, it is treated as an inline function

Outside the class definition


 To write function we need to declare function inside the class and definition (function body) is
written outside the class
 The general form of a member function definition

Return-type classname:: functionname (argument declaration)


{
Function body
}

 The membership label classname:: tells the compiler that the function function-name belongs to
the class classname
 The scope of the function is restricted to the class-name specified in the header line.
 The symbol ::=>scope resolution operator

Example
Void item::getdata(int a, float b) //getdata =>member functions
{
Number =a;
Cost=b;
}
Void item::putdata(void) // putdata =>member functions
{
Cout<<”number:”<<number<<”\n”;
Cout<<”cost:”<<cost<<”\n”;
}

Static member Variables


Synopsis
1. Introduction
2. Characteristics of Static member variables
3. Syntax for static member variables
4. Example for static member variables
5. Example Program Using static member variables
6. Output
Introduction
 Static variable are normally used to maintain values common to the entire class.
 For example, a static data member can be used as a counter that record occurrences of all the
objects.

Characteristics of Static member Variables


 A static member variable has certain characteristic:
1. It automatically initialized zero when the first object is created, no other initialization is permitted.
Where a simple variable have initially garbage value.

7
2. Only one copy of that member is created for entire class and shared by all objects of that class, no
matter how many objects are created.
3. It is visible only within a class, but its life time is the entire program.

Syntax for Static member Variables:

Static data type variable name [size]

Example for Static member functions:


Static char course [15];

Example Program using static member variables

#include<iostream>
using namespace std;
class student{
int roll_no;
char name[15];
static char course[15]; // Static member Variables
public:
void getdata() {
cout<<" Enter roll number:";
cin>>roll_no;
cout<<" Enter Name:";
cin>>name;
}
void putdata() {
cout<<"Student Roll Number: "<<roll_no<<"\n";
cout<<"Student Name: " <<name<<"\n";
cout<<"Student Class: " <<course<<"\n";
}
};
char student::course[15]="BCA";
int main()
{
int n;
cout<<"Enter number of student you want...";
cin>>n;
student s[n]; // array of object
for(int i=0;i<n;i++)
{
cout<<"Detail of student"<<i+1<<"\n";
s[i].getdata();
}
cout<<"\n";
for(int i=0;i<n;i++)
{
cout<<"\n\nStudent"<<i+1<<"\n";
cout<<"--------\n";
s[i].putdata();
}
return 0;
}

8
Output:

Static member functions


Synopsis
1. Introduction
2. Syntax for static member variables
3. Example for static member variables
4. Example Program Using static member variables
5. Output

Introduction
 A member function that is declared static has the following properties
 A static function can have access to only other static members (function or variable) declared in
same class
 A static member function can be called using the class name as follows

Syntax for Static member functions:

Class-name:: function-name

Example for Static member functions:


Test::getdata ( );

Example program using static member function:


#include<iostream>
using namespace std;
class stat_fun
{
int obj;
static int count; // Static member Variables
public:
void stat()
{
obj=++count;
}
void showObject()
{
cout<<"\n object number is: "<<obj;

9
}
static void showcount() // Static member functions
{
cout<<"\ncount object is:"<<count;
}
};
int stat_fun::count;
int main()
{
stat_fun o1,o2;
o1.stat();
o1.stat();
stat_fun::showcount();
stat_fun o3;
o3.stat();
stat_fun::showcount();
return 0;
}

Output:

Arrays of object
Synopsis
1. Introduction
2. Syntax for Array of Object
3. Example
4. For Example using class:
5. Example Program Using Array of Pointers
6. Output
Introduction 7. Explanation about array of pointers
 Arrays are collection of similar data types.
 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.

Syntax for Array of Object


Class_name object_ name [Array size]

Example:
Student s [size];

For Example using class:


Class student
{
Private:

10
Float per;
Public:
int regno, age;
Void getdata ( );
Void show ( );
};
 For this class if we required 100 student, then we are not declare different s1,s2,…,s100 object
because it’s very critical task.
 For this problem we use array of object.

Example Program Using Array of Pointers

#include<iostream.h>
Using namespace std;
Class student
{
Char name [15];
Float age;
Public:
Void getdata ();
Void putdata ();
};
Void student:: getdata()
{
cout<<"Enter Name: ";
cin>>name;
cout<<"Enter Age: ";
cin>>age;
}
Void student:: putdata()
{
cout<<"Name: "<<name<<"\n";
cout<<"Age: "<<age <<"\n";
}
const int size=2;
int main()
{
student s[size]; // array of object
for(int i=0;i<size;i++)
{
cout<<"Detail of student"<<i+1<<"\n";
s[i].getdata();
}
cout<<"\n";
for(int i=0;i<size;i++)
{
cout<<"\n\nStudent"<<i+1<<"\n";
cout<<"--------\n";
s[i].putdata();
}
return 0;
}

11
Output:

Explanation about array of pointers:


 The identifier employee is a user defined data type and
 It can be used to create objects that relate to different categories of the employees

Example
Employee manager [3]; //array of manager
Employee foreman [15]; //array of foreman
Employee worker [75]; //array of worker

 In the above example, the array manager contains three objects (managers) namely
Manager [0]
Manager [1]
Manager [2]
of type employee class
 In the above example, the array foreman contains 15 objects (foreman) namely
Foreman [0]……. Foreman [14]
of type employee class
 In the above example, the array worker contains 75 objects (worker) namely
Worker [0]……. Worker [74]
of type employee class
 The following statement helps to display the elements of array of objects
Manager[i].putdata( );
 The above statement requests the object manager[i] to invoke the member function putdata

Friend function

Synopsis
1. 1.Introduction
2. Syntax of Friend function
3. Example of Friend function
4. Declaration of Friend function
5. Characteristic of friend function
6. Program using friend function
7. Output
8. Advantage of having friend function
9. Disadvantage of having friend function
Introduction
 The functions that are declared with the keyword friend are known as Friend functions
12
 A function can be declared as a friend in any number of classes
 The function declaration should be preceded by the keyword friend
 The function is defined elsewhere in the program like a normal C++ function.
 C++ allows a mechanism, in which a non-member function has access permissions to the
private member of the class.
 This can be done by declaring the non-member function “friend‟ to the class whose private data
is to be accessed.

Syntax of Friend function


Class <class_name>
{
Private:
Private member variables;
Private member functions;
Public:
Public member variables;
Public member function
Friend return_type function_name ( ); //declaring a member function as a friend to the
class
};

Declaration of Friend function


Class acc
{
----
----
Public:
----
----
Friend void showbal (acc); //declaration
};

 For example, consider a two classes, manager and scientist have been defined.
 We would like to use a function income_tax() to operate on the objects of both these classes,
thereby allowing the function to have access to the private data of these classes.

Characteristic of friend function:


1. It is not in the scope of the class which it has been declared as friend.
2. It cannot be called using the object of that class.
It can be invoked like a normal function without the help of object.
3. It cannot access data member directly, it must be use object with dot(.) operator and data
member.
4. Normally it has object as argument.

Program using friend function


/* C++ program to demonstrate the working of friend function */

#include<iostream.h>
#include<conio.h>
Class acc
{
Private:
Char name[20];

13
int accno;
Float bal;
Public:
Void read ( )
{
cout<<”name:”;
cin>>name;
cout<<”a/c no:”;
cin>>accno;
cout<<”balance:”;
cin>>bal;
}
Friend void showbal(acc); //friend function declaration
};
Void showbal( acc a)
{
cout<<”Balance of acc no.”<<a.accno<<” ”is Rs.”<<a.bal;
}
Void main ( )
{
acc k;
k.read( );
showbal(k);
}
 In this pgm,”showbal( )‟ is the non-member function that has the access over the private
member i.e., ‟name‟, “accno‟, “bal‟ of the class
 Just because it has been declared as friend to the class.
 Access to private member is possible.

Advantage of having friend function:


 We can able to access the other class members in our class, if we use friend keyword.
 We can access the members without inheriting the class.
 The function can be defined at any place in the program like normal function.

Disadvantage of having friend function:


 Maximum size of memory will occupied by object according to the size of friend member.
 Break the concept of ‘data hiding’ in oop.

Overloading Member function


Or Function Overloading
Synopsis
1. Introduction
2. Definition of function overloading
3. Declarations of function overloading
4. Example program of function overloading
5. Output

Introduction
It have two or more functions can have same name but different parameters
It is otherwise known as function Overloading.
14
Definition of function overloading
 The process of using same functions name to create functions that perform a variety of
different task is called FUNCTION OVERLOADING.
 The function is based on the following ways
o Different argument –[void add(int a); void add(float a);]
o Different no of argument–[ void add(int a); void add(float a,float b);]
o Different function type-[int disp(), char disp()]
 For eg: add( ) function handles different types of data as shown in below
 If two or more function having same name but different arguments are known as function
overloading

Declarations of function overloading

Int add(int a, int b); //prototype1


Int add (int a, int b, int c); //prototype2
Double add(double x, double y); //prototype3
Doube add(int p,double q); //prototype4
Double add (double p, int q); // prototype5

//Function calls

Cout <<add(5,10); //uses prototype1


Cout<<add(5,10,15) //uses prototype2
Cout<<add(15,10.0); //uses prototype4
Cout<<add(12.5,7.5); //uses prototype3
Cout<< add(0.75, 5); //uses prototype5

Example program of function overloading

#include<iostream.h>
Using namespace std

Void print (int i)


{
Cout<<”The Integer number is: “<<i<<endl;
}
Void print (float f)
{
Cout<<”The floating number is: “<<f<<endl;
}
Void print (char const *c)
{
Cout<<”The Char* is: “<<c<<endl;
}
Int main()
{
Print(10);
Print(10.10);
Print(“ten”);
Return 0;
}

15
Output:
The Integer number is: 10
The floating number is: 10.10
The Char* is: ten
Bit fields and classes
Synopsis
1. Introduction
2. Example
3. Memory size for each data type
4. Advantage of using bit fields

Introduction
 Bit field provides exact amount of bits required for storage of values.
 If variable value is 1 or 0 then a single bit is enough to store it.
 If variable value is 0 or 3 then a 2 bits are enough to store it.
 If variable value is 0 or 7 then a 3 bits are enough to store it.
 The number of bits required for a variable is specified by non-negative integer followed by
colon.

Example;
Class vehicle
{
Unsigned type: 3;
Unsigned fuel: 2;
Unsigned model: 3;
}

Memory size for each data type


 To hold information or values we use variables.
 The variables occupy minimum of
o 1byte for char
o 2 byte for int
o 4 byte for float
o 4 byte for long int
o 8 byte for double and so on.
Advantage of using bit fields:
 Instead of using complete integer if bits are used, space of memory can be saved.
 Bit fields are used to conserve (save) the memory.
 There are some restrictions while using the bit fields,
 Bit fields should have integral type.
 A pointer array type is not allowed.
 Address of bitfield can’t be obtained using & operator.

Sample program using Bitfields


#include<iostream.h>
#include<conio.h>
#define PETROL 1
#define DIESEL 2
#define TWO_WH 3
#define FOUR_WH 4
#define OLD 5
#define NEW 6

16
Class vehicle
{
Private:
Unsigned type: 3;
Unsigned fuel: 2; 0
Unsigned model: 3;
Public:
vechicle( )
{
Type= FOUR_WH;
Fuel= PETROL;
Model=NEW;
}
Void show( )
{
if (model==NEW)
cout<<„„\n New model”;
else
cout<<„„\n Old model”;
cout<<„„Type of vehicle: ”<<type;
cout<<„„Fuel: ”<<fuel;
}
};
void main( )
{
vehicle v;
cout<<„„size of object:”<<sizeof(v);
v.show( );
}

Output:
Size of object: 1
New model
Type of vehicle: 4
Fuel: 1

Constructors and Destructors


Synopsis
1. Introduction
2. Constructor
3. Declaration of Constructor
4. Implicit call of Constructor
5. Explicit call of Constructor
6. Features of constructor
7. Rules for constructor definition and usage
8. Types of Constructor
9. Destructor
10. Features of destructor
11. Rules for destructor definition and usage
12. Example program

17
Introduction
 Constructor constructs the objects and destructor destroys the objects.
 The compiler automatically executes these functions.
 Constructor is executed when the object is created and destructor is executed at the end of the
function when object goes out of the scope.

Constructor
 A constructor is a special member function.
 Constructor has the same name as that of the class name.
 Constructor is used to construct the objects.

Declaration of Constructor

/* class with constructor */


Class student
{
Private:
Int rollno;
Float marks;
Public:
Student ( ) //constructor
{
rollno=0;
marks=0.0
}
};

 Constructor can be called in two ways


 They are
a. Implicit
b. Explicit

Implicit call of Constructor

Class student //class


{
Private:
Int rollno;
Float marks;
Public:
Student( ) //Constructor
{
rollno=0;
marks=0.0
}
};
Void main()
{
Student s1; //Implicit call
}

18
Explicit call of Constructor

Class student //class


{
Private:
Int rollno;
Float marks;
Public:
Student( ) //Constructor
{
rollno=0;
marks=0.0
}
};
Void main()
{
Student s1=student ( ); //Explicit call
}

Features of constructor
 Constructor has the same name as class
 It does not have any return type not even void
 Constructor can be declared only in public section of the class
 Constructor is called automatically when the object of the class is created

Functions of constructor
1. The constructor function initializes the class object
2. The memory space is allocated to the object

Rules for constructor definition and usage


1. The name of the constructor must be same as that of the class
2. A constructor can have parameter list
3. The constructor function can be overloaded
4. The compiler generates a constructor, in the absence of user defined constructor
5. The constructor is executed automatically

Types of Constructor
 There are three types of Constructor.
 They are
1. Default constructor
2. Parameterized constructor
3. Copy constructor

Default constructor
 A constructor that accepts no parameter is called the default constructor
 It have no argument
 It is used to initialize an object of a class with legal initial values

Example program
Class student //class
{
Private:
Int rollno;

19
Float marks;
Public:
Student( ) //Constructor
{
rollno=0;
marks=0.0
}
Void display ( );
Void enter ( );
};
Void main()
{
Student s1; //default constructor called
}

Parameterized constructor

 A constructor that accepts parameters for its invocation is known as parameterized


constructor
 It also called as regular constructor
 It accepts arguments
 It initializes the data members of the object with the arguments passed to it
 When the object s1 is created, default constructor is called and
 when the object s2 is created parameterized constructor is called and this is implicit call of
parameterized constructor
 When the object s3 is created again the parameterized constructor is called but this explicit
call of parameterized constructor

Example program
Class student //class
{
Private:
Int rollno;
Char name[20];
Float marks;
Public:
Student ( ) //Constructor
//default constructor
{
rollno=0;
marks=0.0
}
Student (Int roll, char nam[20],float mar)
//parameterized constructor
{
Rollno=roll;
Strcpy(name, nam);
Marks=mar;
}
Void display ( );
Void enter( );
20
};
Void main ( )
{
Student s1;
Student s2 (1,”ramesh”, 350);
Student s3=student (2,”kajal”, 400);
}

Copy constructor
 It is a special constructor in the C++ programming language
 It is used to create a new object as a copy of an existing object
 It accepts an objects as an argument
 It creates a new object and initializes its data members with data members of the object passed
to it as an argument

Syntax

Class_name(class_name & object_name)


{

Example program:
Class student //class
{
Private:
Int rollno;
Char name[20];
Float marks;
Public:
Student ( ) //Constructor
//default constructor
{
rollno=0;
marks=0.0
}
Student (Int roll, char nam[20],float mar)
//parameterized constructor
{
Rollno=roll;
Strcpy(name, nam);
Marks=mar;
}
Student (student &s) //copy constructor
{
Rollno=s.rollno;
Strcpy(name, s.name);
Marks=s.marks;
}
}
Void main ( )
{
Student s1; //statement1

21
Student s2 (1,”ramesh”, 350); //statement2
Student s3(S2); //statement3
Student s4 (2,”Kajal”, 320); //statement4
Student s5=s4; //statement5
}

Constructor overloading
 C++ allows more than one constructors to be defined in a single class
 Defined more than one constructors in a single class provided they all differ in either type or
number of argument is called constructor overloading

Example program:
Class student //class
{
Private:
Int rollno;
Char name[20];
Float marks;
Public:
Student ( ) //default constructor
{
rollno=0;
marks=0.0
}
Student (Int roll, char nam[20],float mar) //parameterized constructor =>1
{
Rollno=roll;
Strcpy(name, nam);
Marks=mar;
}
Student (Int roll, char nam[20]) // parameterized constructor=>2
{
Rollno=roll;
Strcpy(name, nam);
Marks=100;

Student (student &s) //copy constructor


{
Rollno=s.rollno;
Strcpy(name, s.name);
Marks=s.marks;
}
}
 In the class student there are 4 constructors
1=>default constructor
2=>parameterized constructor
1=>copy constructor

 Defining more than one constructor in a single class is called constructor overloading
 We can define as many parameterized constructors as we want in a single class provided they
all differ in either number or type of arguments

22
Dynamic constructor
 The constructors can also be used to allocate memory while creating objects.
 This will enable the system to allocate the right amount of memory for each object when the
objects are not of the same size
 Allocation of memory to objects at the time of their construction is known as dynamic
construction of objects.
 The memory is created with the help of the new operator.

Destructor
 A destructor is a special member function
 Destructors are opposite to constructor.
 The process of destroying the class objects created by constructor is done in destructor.
 The destructor has the same name as the class name, preceded by a tilde (~).
 A destructor is automatically executed when the object goes out of the scope.
 A class should have only one destructor.

Declaration of Destructor
~ class name

Example program:
#include<iostream.h>
Class student
{
Public:
Student ( )
{
cout<<”Constructor called”;
}
~student ( )
{
cout<<”Destructor called”;
}
};
Void main ( )
{
clrscr( );
Student s;
}

OUTPUT:
Constructor called
Destructor called

Features of Destructor
 It has the same as that of class and preceded by tilde sign(~)
 It is automatically by the compiler when an object goes out of scope
 Destructors are used to deallocate memory
 It performs other cleanup for a class object and its class members when the object is destroyed.
 It always declared in the public section of the class
 We have only one destructor in a class

23
Rules for destructor definition and usage
 The destructor has the same name as that of the class prefixed by the tilde character
 The destructor cannot have arguments
 It has no return type
 Destructors cannot be overloaded i.e., there can be only one destructor in class
 In the absence of user defined destructor, it is generated by the compiler
 The destructor is executed automatically when the control reaches the end of class scope

All the Best

24

You might also like