C++ notes unit 3
C++ notes unit 3
Derived data types: The data-types that are derived from the primitive or built-in
data types. Array, String and Pointer are the derived data types.
Array:
A collection of related data items of similar data type stored in contiguous
memory locations.
Elements of an array can be accessed using their indices.
Indexing of an array starts from 0. It means the first element is stored at the
0th index, the second at 1st, and so on.
Once an array is declared its size remains constant throughout the program.
An array can have multiple dimensions.
Advantages:
o Code Optimization (less code)
o Random Access
o Easy to traverse data
o Easy to manipulate data
o Easy to sort data.
Disadvantages:
o Fixed size
Array types:
1. Single Dimensional Array
2. Multidimensional Array
Example:
int Arr[5];
Priya M R 1
Unit III C++
Here, Arr is declared to be an array of int type and of size five. Five contiguous
memory locations get allocated as shown below to store five integer values.
Each data item in the array Arr is identified by the array name followed by pair
of square brackets enclosing a subscript value. The subscript value ranges from 0
to 4, i.e., Arr[0] denotes first data item Arr[1] denotes second data item and so
on. Arr[4] denotes the last data item.
where, data-type refers to the data type of the array elements. variable-name refers
to the name of the array. {value0, valuel,..., valuesize-1} are constant values. The
values {value0, valuel,..., valuesize-1} are called initializer-list for the array.
Example:
int a [5] = { 2, 5, 6, 8, 9 };
Example program:
#include<iostream>
Using namespace std;
int main (void)
{
int a [5]={2,5,6,8,9}, i;
cout << "The values in the array are: \n";
for (i = 0; i < 5; i++)
cout << "a[" << i << "] = " << a[i] << endl;
return 0;
}
Priya M R 2
Unit III C++
Output:
The values in the array are
a[0] = 2
a[l] = 5
a[2]= 6
a[3] = 8
a[4] = 9
Multidimensional Arrays:
An array with more than one subscript is called a multidimensional
array.
Example: arrays of two dimensions (2-d arrays), arrays of three dimensions (3-d
arrays), arrays of four dimensions (4-d arrays) and so on.
Where, data-type refers to any valid data type, variable-name refers to the
valid identifier, rowsize indicates the no. of rows and colsize indicates the no. of
elements in each row.
rowsize and colsize should be integer constants. Total no. of locations
allocated will be equal to rowsize * colsize.
Each element in a 2-d array is identified by the array name followed by a
pair of square brackets enclosing its row-number, followed by a pair of square
brackets enclosing its column-number. Row-number ranges from 0 to rowsize – 1
and column-number ranges from 0 to colsize – 1.
Example:
int b[3] [3];
‘b’ is declared to be an array of two dimensions and of data type int. rowsize
is 3 and colsize is 3. Memory representation of ‘b’ array.
.
Priya M R 3
Unit III C++
Each data item in the array ‘b’ is identifiable by specifying the array name
‘b’ followed by a pair of square brackets enclosing row number, followed by a
pair of square brackets enclosing column number.
b[0] [0] refers to data item in the first row and first column.
b[0] [1] refers to data item in the first row and second column.
b[2] [2] refers to data item in the third row and third column.
b[2] [0] refers to data item in the third row and first column.
Where, data-type refers to any basic data type. variable-name refers to array
name. rowsize indicates the no. of rows, colsize indicates the no. of columns of the
array. initializer-list is a comma separated list of values of type data-type or
compatible with data-type.
If the no. of values in initializer-list is equal to the product of rowsize and
colsize. The first rowsize values in the initializer-list will be assigned to the first
row, the second rowsize values will be assigned to the second row of the array and
so on.
Example:
int matrix[2][3]={10,20,30,40,50,60};
Since colsize is 3, the first 3 values of the initializer-list are assigned to the
first row and the next values are assigned to the second row.
10 20 30
40 50 60
int matrix[2][3]={{10,20,30},{40,50,60}};
Priya M R 4
Unit III C++
Example program:
#include<iostream>
using namespace std;
int main ()
{
int a[2][2] = { 1, 2, 3 , 4 } ;
int i, j;
cout << "Matrix a: \n";
for (i= 0 ; i < 2; i++)
{
for (j =0; j < 2; j++)
cout <<"\t" << a[i][j];
cout << "\n ";
}
return 0;
}
Output:
Matrix a:
12
34
Example:
int a[2][2][3];
‘a’ is declared to be a 3-d array. It can accommodate two tables of values, each
table having two rows and three columns. Each element in the array is identified by
the array name ‘a’, as follows:
a[0][0][0] indicates data item in first table, first row, first column.
a[1][0][0] indicates data item in second table, first row, first column.
a[1][1][2] indicates data item in second table, second row, third column.
Priya M R 5
Unit III C++
Initialization of Three-dimensional (3-D) array:
int b[2] [2] [2] = {{{1,2},{3,4}},{{5,6},{7,8}}};
Output:
Table1
12
34
Table2
56
78
String:
A sequence of characters terminated by the special character ’\0’.
Declaration of string:
char s[20];
Initialize of string:
Example1:
char strl[5] = {'a', 's', 'd', 'f', '\0'};
Here, strl is declared to be a string variable with size five. The initializer-list
consists of comma separated character constants. Null character '\0 is explicitly
listed.
Example2:
char str2[5]= {"asdf"};
Here, str2 is also declared to be a string variable of size five. The initializer-
list consists of a string constant. Null character '\0' will be automatically appended
to the end of string by the compiler.
Example program:
#include <iostream>
using namespace std;
int main ()
{
char s1[10], s2[10]={"Welcome"};
cout << "Enter a string into s1\n";
Priya M R 6
Unit III C++
cin >> s1;
cout << "s1 = " << s1 << "\n";
cout << "s2 = "<<s2;
return 0;
}
String Manipulations:
The most commonly performed operations over strings are
1. Finding the length of a string
2. Copying one string to another string
3. Concatenation of two strings
4. Comparing two strings
5. Searching substring in a string
String manipulation built-in functions are declared in the header file
string.h.
Finding the length of a string:
strlen(): it is used to find length of a string. It defines no. of characters
excluding the null character \0.
The prototype of strlen () is as follows:
int strlen (s );
Example:
char s[20] = { "Welcome to India" };
int l;
l = strlen(s);
strcpy(s1,s2);
Here the string constant "XYZ" gets copied to sl. sl now contains "XYZ".
Example1:
char s1[20]={ "abc"}, s2[20]={ "aac"};
int i;
i = strcmp (sl, s2);
Example2:
char sl[20]={"aac"}, s2[20]={"abc"}:
int i;
i = strcmp (s1, s2);
Priya M R 8
Unit III C++
Example3:
char sl[20]={"abc"}, s2[20]={"abc"}:
int i;
i = strcmp (s1, s2);
The process of appending one string to the end of another string is called
concatenation of two strings.
Example:
char sl[10] = {"abc"}, s2[10] = {"xyz"}:
strcat (sl, s2) ;
now s1 value is "abcxyz".
Syntax:
char *strstr (const char *s1, const char *s2);
Priya M R 9
Unit III C++
Example:
char sl[10] = {"Object Oriented"}, s2[10] = {"Or"};
int p=strstr (sl, s2) ;
Pointer:
Pointer is a variable, it is also known as locator or indicator that points to an
address of another variable.
Example:
int *ptr;
Pointer operators: two special operators known as pointer operators. They are &
and *.
& stands for ‘Address of’ and it is used retrieve the address of a variable.
* stands for 'value at address’ and it is used to access the value at a location
by means of its address. Asterisk(*) is called as dereference operator.
Example:
int number=30;
int ∗p;
p=&number;
Pointer ‘P’ stores the address of number variable. The pointer variable and the
referring variable data type should be same.
Priya M R 10
Unit III C++
Example Program:
#include <iostream>
using namespace std;
int main()
{
int number=30;
int ∗p;
p=&number; //stores the address of number variable
cout<<"Address of number variable is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
return 0;
}
Output:
Address of number variable is: 0x7ffccc8724c4
Address of p variable is: 0x7ffccc8724c4
Value of p variable is: 30
Pointer Arithmetic
Pointer arithmetic operators are:
1. Incrementing and Decrementing Pointers
2. Addition of Constant to Pointers
3. Subtraction of Constant from Pointers
4. Subtraction of Two Pointers of the Same Type
5. Comparison of Pointers
6. Assigning one pointer to another pointer.
Priya M R 11
Unit III C++
Priya M R 12
Unit III C++
ptr - 5
Example:
int x = 5, y = 7;
int *p = &y;
int *q = &x;
p - q;
o Comparison of Pointers
We can perform a comparison between the two pointers using the
relational operators(>, <, >=, <=, ==, !=). We generally use this operation
to check whether the two-pointer as pointing to the same memory location
or not.
Example:
int arr[5];
// declaring pointer to array name
int *ptr1 = &arr;
// declaring pointer to first element
int *ptr2 = &arr[0];
ptr1 == ptr2; // Both point to same memory location
Priya M R 13
Unit III C++
o Assigning one pointer to another pointer.
Example:
int n=10; // a variable
int *ptr1= &n; // a pointer to that variable
int *ptr2; // another pointer
ptr2=ptr1;
Pointer ptr1 assigning to pointer ptr2. Both pointers pointing to the same
location.
C++ stream:
A stream is a sequence of bytes. It acts either as a source from which the
input data can be obtained or as a destination to which the output data can be sent.
The source stream that provides data to the program is called the input
stream and the destination stream that receives output from the program is called
the output stream as shown in figure.
Priya M R 14
Unit III C++
As in figure above ios is the base class for istream(input stream) and
ostream(output stream) which are base classes for iostream(input/output stream).The class ios is
declared as the virtual base class so that only one copy of its members are inherited by
the iostream.
The class ios provides the basic support for formatted and unformatted
input/output operations.The class istream provides the facilities for formatted and unformatted
input while the class ostream(through inheritance) provides the facilities for formatted output.
The class iostream provides the facilities for handling both input output streams.Three
classes namely istream_withassign, ostream_withassign and iostream_withassign add assignment
operators to these classes.
Stream classes for console operations:
Priya M R 15
Unit III C++
Unformatted I/O Operations: Unformatted I/O is used to read and write data as a
stream of bytes without any format.
Unformatted I/O Operations are:
1. cin and cout
2. get( ) and put( )
3. getline( ) and write( )
Example:
int x=10;
cout<<″Welcome″; // display Welcome on screen
cout<<″x=″<<x; // display x=10 on screen
cin: The cin is a predefined object of istream class. It is connected with the
standard input device, which is usually a keyboard. The cin is used in
combination with stream extraction operator (>>) to read the input from a
console.
Syntax:
cin >> variable1>>variable 2>>…..>> variableN;
variable1, variable2. ...are valid C++ variable names that have been declared
already. This statement will cause the computer to stop the execution and read
input data from the keyboard.
The operator >> reads the data character by character and assigns it to the
indicated location. The reading for a variable will be terminated at the encounter of
a white space character.
Priya M R 16
Unit III C++
Example:
int code;
cin >> code;
Example program:
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "Enter x value:" << endl;
cin>>x;
cout<<"x="<<x;
return 0;
}
Output:
Enter x value: 100
x=100
Priya M R 17
Unit III C++
Example:
The get(char) version is used as follows
char c;
cin.get( c ); //get a character from the keyboard and assigns it to ‘c’.
put(): The function put() is a member of ostream class. It is used to read single
character. Since this function is member of output Stream classes, these must be
invoked using cout object.
Example:
cout.put(‘x’);
displays the character x and
cout.put(ch);
displays the value of variable ch.
Example program:
#include <iostream.h>
using namespace std;
int main()
{
char c;
cout<<”Enter a character: \n”;
cin.get(c);
cout<<”Character is:\n”;
cout.put(c);
return 0;
}
Priya M R 18
Unit III C++
getline() and write() functions
getline(): The getline() function reads a whole line of text that ends with a newline
character. This function can be invoked by using the object cin as follows:
Syntax:
cin.getline(line,size);
This function call invokes the function getline() which reads character input
into the variable line. The reading is terminated as soon as either the newline
character ‘\n’ is encountered or size-1 characters are read. The newline character is
read but not saved. Instead it is replaced by the null character.
Assume that we have given the following input through key board:
Object Oriented
This input will be read and assigned to the character array name.
Output:
Object Oriented Programming
Example program:
int main()
{
int size = 20;
char city[20];
cout<< "Enter city name: \n";
cin.getline (city, size);
cout << "City name is: ";
cin.getline(city, size);
return 0;}
Priya M R 19
Unit III C++
Formatted I/O Operations: Formatted I/O operations involve reading or writing
data in a specific format.
Different ways of formatting the output are:
1. ios class functions and flags.
2. Manipulators
2. precision(): The precision method is used to set the number of the decimal
point to a float value.
Syntax:
cout.precision(d);
where d is the number of digits to the right of the decimal point.
Example:
cout.precision (3);
cout << sqrt(2) << "\n";
cout << 3.14159 << "\n";
cout << 2.50032 << "\n";
Priya M R 20
Unit III C++
Output:
1.141 (truncated)
3.142 (rounded to the nearest cent)
2.5 (no trailing zeros)
3. fill(): The fill method is used to set a character to fill in the blank space of a
field.
Syntax:
cout.fill(ch);
Where ch represents the character which is used for filling the unused
positions.
Example:
cout.fil1(*);
cout.width(10);
cout << 5250 << "\n";
Output:
* * * * * * 5 2 5 0
4. setf(): The setf method is used to set various flags for formatting output. The
setf(), a member function of the ios class.
Syntax:
cout.setf(argl , arg2);
The arg1 is one of the formatting flags defined in the class ios. The
formatting flag specifies the format action required for the output.
The arg2, known as bit field specifies the group to which the formatting flag
belongs.
Table(1) shows the bit fields, flags and their format actions. There are three
bit fields and each has a group of format flags which are mutually exclusive.
Priya M R 21
Unit III C++
Examples1:
cout.setf(ios::left, ios::adjustfield);
cout.setf(ios::scientific, ios::floatfield);
Example2:
cout.fi11(*);
cout.setf(ios::left, ios:: adjustfield);
cout.width(15);
cout << "TABLE 1" << "\n";
Output:
T A B L E 1 * * * * * * * *
Example:
cout.setf(ios::showpoint); // The flags without bit fields
cout.setf(ios::showpos); // The flags without bit fields
cout.precision (3);
cout.setf (ios::fixed, ios::floatfield);
cout.setf (ios::internal, ios::adjustfield);
cout.width(10);
cout << 275.5 << "\n";
Output:
+ 2 7 5 . 5 0 0
Priya M R 22
Unit III C++
5. unsetf(): The unsetf method is used To remove the flag setting.
Syntax:
unsetf(arg1);
Example:
cout.setf (ios::hex, ios::basefield ); // set hex as the basefield
cout.setf (ios::showbase); // activate showbase
cout << 100 << '\n';
cout.unsetf(ios::showbase ); // deactivate showbase
cout << 100 << '\n';
Output:
0x64
64
Note: The Definition of manipulators is same as ios class function and also flags.
Refer the same.
Priya M R 23
Unit III C++
Example1:
cout << setw(10) << 12345;
Example2:
cout<< setw(5) << setprecision (2) << 1.2345
<<setw(10) << setprecision(4) << sqrt (2)
<<setw(15) << setiosflags (ios::scientific) << sqrt (3);
<< endl;
This will print all the three values in one line with the field sizes of 5, 10,
and 15 respectively. Each output is controlled by different sets of format
specifications.
Where, class is the keyword. The class-name is any user-defined name. The
body of a class is enclosed within braces and terminated by semicolon. The class
body contains the declaration of variables and functions. These functions and
variables are collectively are called class members.
The private class members can be accessed only from within class. Public
members can be accessed from outside the class. The default visibility mode is
private.
Priya M R 24
Unit III C++
The variables declared inside the class are known as data members and the
functions are known as member functions.
Example:
class item
{
int number;
float cost;
public:
void getdata(int a, float b);
void putdata(void);
};
Item is the class name. The class item contains two data members and two
function members. The number and cost are data members are declared as private
by default, and getdata() and putdata() functions are declared as public. The
function getdata() can be used to assign values to the member variables number
and cost, and putdata() for displaying the their values.
Instance variable:
Instance Variables are declared inside a class and are used to store values in
an object. Each object has its own copy of instance variables.
Instance variable creation, Syntax:
data-type variable-name1, variable-name2,…., variable-nameN;
Where, data-type can be any basic data-type. Variable-name can be any
valid identifier. List of variables are separated by comma.
Example: int a,b,c;
In this, variables a,b,c are declared as int type.
Priya M R 25
Unit III C++
In this example, ‘x’ and ‘y’ are objects of data class. ‘Name’ and ‘age’ are
instance variables of class data. Data members can be declared within the class as
public, private, or protected data. Each object has its own copy of instance
variables. As shown in figure below.
x y
Name Name
age age
Member Methods:
A member function in C++ is a function that is part of a class. It is used read,
manipulate, or display all types of data members of the class. Member functions are
also known as methods.
Member Functions can be declared within the class as public, private, or
protected functions.
There are mainly two ways to define Member Function in C++.
1. Definition within the Class
2. Definition outside the Class
Example:
class info
{
void display()
{
cout<<″Object Oriented Program″;
}
};
In this example, display() is a member function of info class. Which is define
inside the class.
Priya M R 26
Unit III C++
Defining Member Function outside the Class:
We can define the member function outside the class using the scope
resolution operator (::). While using this method we need to ensure that the
function is declared within the class.
Syntax:
return_type class_name::function_name (parameter-list)
{
// definition of the function
}
Example:
class Circle
{
int size;
public:
void printSize(int s);
};
void Circle :: printSize(int s)
{
cout<< s <<endl;
}
Object:
Object is an instance of a class. All the members of the class can be accessed
through object.
A class provides the blueprints for objects, an object is created from a class.
Syntax:
class-name object-name1,object-name2,….,object-nameN;
Priya M R 27
Unit III C++
Where, class-name is name of the class which has declared previously.
Object-name is the name of any valid identifier, objects are separated by comma.
The objects listed is belongs to particular class. When the object is created memory
is allocated for the data members of particular class.
Example:
Circle C1, C2;
In this example, Circle is a class-name. C1 and C2 are the objects of Circle
class.
Accessing Members:
Accessing a data member depends on the access control (public, private and
protected) of that data member.
If it’s public, then the data member can be easily accessed using the direct
member access (.) operator with the object of that class.
If, the data member is defined as private or protected, then we cannot access
the data variables directly.
Syntax:
Object-name.member-name;
Example:
data d1;
d1.x=10;
d1.set(10,20);
In this example, d1 is the object of data class. ‘x’ is the data member of data class.
set() function is the member function of data class. These data members are
accessed using object name and dot(.) operator.
Example:
class data
{
public:
int x,y;
void set(int x1,int y1) //function define inside the class
{
x=x1;
y=y1;
}
Priya M R 28
Unit III C++
void display( ); // function declaration
};
void data::display( ) // function defined outside the class
{
cout<<″x=″<<x<<endl;
cout<<″y=″<<y<<endl;
}
int main()
{
data d1,d2; // Creating an object x and y of the class data
d1.set(10,20); //Accessing the member function
d2.x=100; //Accessing the data member
d2.y=200;
d1.display( );
d2.display( );
return 0;
}
Access specifiers
Access specifiers or Access Modifiers in a class are used to assign the accessibility to the
class members, i.e., they set some restrictions on the class members. There are three access
specifiers:
1. Public
2. Private
3. Protected.
Inside the class all these access specifier can be used, the keywords and followed by colon.
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
Priya M R 29
Unit III C++
}
};
int main()
{
Circle obj;
obj.radius = 5.5;
Output:
Radius is: 5.5
Area is: 94.985
In the above program, the data member radius and function compute_area() is
declared as public so it could be accessed anywhere and thus was allowed
access from inside main() using object name with the direct member access
operator (.).
class Circle
{
// private data member
private:
double radius =1.5;
};
// main function
int main()
{
// creating object of the class
Circle obj;
cout << "Area is:" << obj.compute_area();
return 0;
}
Output:
Area is: 7.065
In this program, radius is a private variable, we cannot access inside main() like
Obj.radius=1.5;
Will get error.
};
Priya M R 31
Unit III C++
// sub class or derived class from public base class
class Child : public Parent
{
public:
void setId(int id)
{
// Child class is able to access the inherited
// protected data members of base class
id_protected = id;
}
void displayId()
{
cout << "id_protected is: " << id_protected << endl;
}
};
int main()
{
Child obj1;
obj1.setId(81);
obj1.displayId();
return 0;
}
Output:
id_protected is: 81
Priya M R 32
Unit III C++
this pointer
this is a keyword that refers to the current instance of the class. Usages of
this keyword are:
It can be used to pass current object as a parameter to another method.
It can be used to refer current class instance variable.
It can be used to declare indexers.
Syntax:
this->members;
Example:
this->x;
Here, this is the keyword which points to current object. ‘x’ is the data member of
the class.
Example program:
#include<iostream>
using namespace std;
Priya M R 33
Unit III C++
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
Output:
x = 20
Friend function
It is used to access all private and protected members of the class.
It is a non-member function or ordinary function of a class.
A friend function of a class is declared inside the class and defined outside
that class.
They are declared using the keywords friends.
Syntax:
function declared inside the class:
friend return_type function_name (arguments);
To define friend function outside the class, no need to specify the friend
keyword, class name and scope resolution operator (::). Like normal
function we can define friend function.
Priya M R 34
Unit III C++
Characteristics of a Friend function:
The function is not in the scope of the class to which it has been declared
as a friend.
It cannot be called using the object as it is not in the scope of that class.
It can be invoked like a normal function without using the object.
It cannot access the member names directly and has to use an object name
and dot membership operator with the member name.
It can be declared either in the private or the public part.
Example program:
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box()
{ length=0;}
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
Output:
Length of box: 10
Priya M R 35
Unit III C++
Constructor:
Characteristics of Constructors:
The name of the constructor is the same as its class name.
Constructors are mostly declared in the public section of the class.
Constructors do not return values.
A constructor gets called automatically when we create the object of the
class.
Types of constructors
1. Default constructor
2. Parameterized constructor
3. Copy constructor
1. Default Constructor
A default constructor is a constructor that doesn’t take any argument.
It has no parameters. It is also called a zero-argument constructor. When the
object is created default constructor is invokes implicitly.
Here, classname and function name should be same, no return type and
no parameter.
Example Program:
#include <iostream>
using namespace std;
class Employee
{
Priya M R 36
Unit III C++
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main()
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Output:
Default Constructor Invoked
Default Constructor Invoked
2. Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It
is used to provide different values to distinct objects.
These arguments help initialize an object when it is created.
Here, classname and function name should be same, no return type and
but contains parameters.
Priya M R 37
Unit III C++
Example program:
#include <iostream>
using namespace std;
class Employee
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
Employee(int i, string n)
{
id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name<<" "<<endl;
}
};
int main()
{
Employee e1 =Employee(101, "Sonoo"); //creating an object of Employee
Employee e2=Employee(102, "Nakul");
e1.display();
e2.display();
return 0;
}
Output:
101 Sonoo
102 Nakul
Priya M R 38
Unit III C++
3. Copy Constructor
A member function known as a copy constructor initializes an item using
another object from the same class
Here, classname and function name should be same, no return type and
but contains parameters as reference to an object of the same class.
Example program:
#include <iostream>
using namespace std;
class A
{
public:
int x;
A(int a) // parameterized constructor.
{
x=a;
}
A(A &i) // copy constructor
{
x = i.x;
}
};
int main()
{
A a1(20); // Calling the parameterized constructor.
A a2(a1); // Calling the copy constructor.
cout<<a2.x;
return 0;
}
Priya M R 39
Unit III C++
Output:
20
In this example, A(A &i) is the copy constructor, which has object as
parameter. A a2(a1); is calling the copy constructor, in this passing object ‘a1’ as
parameter value.
Destructor:
Destructor is an instance member function that is invoked automatically
whenever an object is going to be destroyed.
Characteristics of a Destructor
A destructor is also a special member function like a constructor. Destructor
destroys the class objects created by the constructor.
Destructor has the same name as their class name preceded by a tilde (~)
symbol.
It is not possible to define more than one destructor.
The destructor is only one way to destroy the object created by the constructor.
Hence, destructor cannot be overloaded.
It cannot be declared static or const.
Destructor neither requires any argument nor returns any value.
It is automatically called when an object goes out of scope.
Destructor release memory space occupied by the objects created by the
constructor.
In destructor, objects are destroyed in the reverse of an object creation.
Example program:
#include <iostream>
using namespace std;
class Test
{
public:
// User-Defined Constructor
Test()
{
Priya M R 40
Unit III C++
cout << "\n Constructor executed";
}
// User-Defined Destructor
~Test()
{
cout << "\nDestructor executed";
}
};
main()
{
Test t;
return 0;
}
Output
Constructor executed
Destructor executed
Priya M R 41