0% found this document useful (0 votes)
43 views10 pages

C++ Part V Constructors and Destructors

Constructors are special member functions that are used to initialize objects when they are created. Constructors have the same name as the class and do not have a return type. They are automatically called when an object is instantiated and can be used to set initial values for data members. If no constructor is defined, the compiler provides a default constructor. Memberwise initialization allows copying values from one object to another without calling the constructor. Constructors can also take arguments to allow initializing values from user input.
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)
43 views10 pages

C++ Part V Constructors and Destructors

Constructors are special member functions that are used to initialize objects when they are created. Constructors have the same name as the class and do not have a return type. They are automatically called when an object is instantiated and can be used to set initial values for data members. If no constructor is defined, the compiler provides a default constructor. Memberwise initialization allows copying values from one object to another without calling the constructor. Constructors can also take arguments to allow initializing values from user input.
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/ 10

C++ PART V

Constructors and Destructors


Every time an object is created we know that memory is allocated to it. So
memory is allocated only during object creation not during the class creation. Member
variables or data members, they are not initialized when we declare a class. As we have
seen in the previous session inside a class we have variables strings integers or float
values but if you see that they have not been given any particular value only their names
would have been defined. The main purpose of this constructor is to do the initialization
function. Member variables within a class cannot be initialized at the time of declaration.
So though you declare a class and you define its body you give it member function and
you give it variables. The value of the variables cannot be given at the time you declare a
class. So that is a rule in C++ .So that is a reason why we go in for this concept of
constructors. So here is an example.
class cal
{
int num1=10;
float num2=15.23;
};
Here we having an class called CAL, We are having the class body which has two
variables one of type integer, name is NUM 1, one of type float, name is NUM 2 .and
here the values for num 1 and num 2 have been given in the class declaration which is
invalid .The class body ends here .Both these declarations and initialization of values to
these declared variables is invalid. So this kind of initialization is not allowed inside
classes in C++.Then how are we going to give values to these variables. One way is we
can get it from the user. The other way is this definition of this constructor. An
initialization function that assigns initial values to the variables declared in the program is
called the constructor function. This function is invoked as soon as the object is created.
So as we have seen every class has a data member and a member function. when an
object for a class memory is allocated based on what the memory can be allocated every
object has a copy of the member function and the separate copy of the data member .So
the data member is going to be an integer 2 bytes or 4 bytes is going to be allocated .If a
character is going to be a member 1 byte is going to be allocated .So based on the number
and types of variables declared inside the class when an object is crated the memory is
going to be allocated .When the value is given for those data variables it can be given
using this constructor function. When is this constructor function called? When there is a
function you have to call it you have to send a message to it asking it to execute only then
they function will get executed. So constructor is nothing but a function which performs
this task of initial values. So when that is function called. That function is called when the
object is created .So a constructor is an initialization function defined inside a class which
is called when the object for that particular class is created .Every time an object is

created for a class the function is called. What is the definition of constructor s .They are
member functions of a class that have the same name as the class name .it is different
from the other functions declared in a class because it is having the same name as the
class name. They are invoked when an instance of the class instance of the class is
nothing but the object. Invoked when an object of that particular class is created .is used
for the initialization of data members or member variables, they do not return values. The
two main points in which these constructors differ from other normal functions is their
name. They have the same name as the class .the second thing is they cannot return any
value. They dont have a return type you dont say void or int or float before the name of
the constructor .You just give the constructor name and the parameters .this is an example
of how to declare constructors.
class ca{
private:
int num; float num2;
Pubic:
cal()
{
num1=0;num2=0.0;}};
You have the class key word called cal the body of the class is open you have the
private access specified you are having two variables integer and float you are having the
public data which is nothing but a cal member functions if you see the CAL is same as
the class name CAL .That is called the constructor function .You are opening the body of
the constructors and you are initializing it with values , NUM1 you are saying 0 because
it is of integer type NUM2 you are giving 0,0 because it is of type float .So this is the way
constructors are declared inside C++ having the same name as the class name. If you see
this particular name cal and this particular name are the same .So it has the same name as
the class name followed by opening and closing brackets and there is no return type .their
is nothing mentioned here void or integer or float because they dont have any return
value and you are having the initialization part being done here .Remember the
initialization of all the members is done here num1 is also given a value num2 is also
given a value .And the body of the constructor is closed like you close another normal
function the class is closed with this semi colleen so this is how you declare constructors
in C++ .Now in case that there are no constructors declared for a class the complier itself
creates a default constructor .default in the sense when nothing specifically is mentioned
the complier will take up that particular option .So how is a default constructor invoked
.the insantation of an object of the class invokes the default constructor .The default
constructor is not returned by the program. it is not even visible to the program .the
complier itself creates a default constructor and initializes all the member variables and
data members that are declared inside the class for that particular object to 0 values. So
this default constructor called is by the computer when the programmer fails to create a
constructor for the class and it is called like any other normal constructor. When ever an
object is created for the class the default constructor is called by the complier. In certain
cases class constructors are not invoked to initialize a newly defined class object.

Now according to the normal protocol whenever an object is created the


corresponding constructor is called and the values are initialized .Certain cases even
when an object is created the particular constructor is not called, That is in situation
where you create one object and give it values from another object .you copy the values
of one object to another object. Like you see in this example .when one object is
initialized to another object you dont require an initialization function over there .The
main reason for a constructor is to initialize a data with values. When we are using the
values from another object there is no point in calling a constructor separately .here if you
see we are having CAL which is the name of the class followed by the object name
OB1.So when this object is created the constructor will be invoked. using that object you
are calling some function DISP next statement if you see you are creating another object
OB2 class name followed by the object name CAL OB2 is equal to OB1 .so according to
this assignment operator .What ever values comes to the right of the is equal to sign is
assigned to the left of the assignment operator .So what ever values have been initialized
to the object OB1 Are simply copied to the object OB2 .so in this case the constructor
value need not be called because the values are initialized in this statement itself. This
method creates object 2 as a bit by bit copy of object1 .and that is called member wise
initialization .from one member another member is initialized. So in this case you dont
need a constructor function at all. Like constructors simply work like other functions like
in other functions you have arguments isnt it the actual arguments and formal arguments
like that in constructors also you have parameters. Only difference between the other
functions and this is that they dont have a return type and the name of the constructor.
When variables need to be initialized with user defined values, now previously if you see
in the constructor all the variables have to be initialized values in the program itself .like
you give CAL opening and closing brackets and you say num is 0 and the float is 0.0 that
is all. So those values have to be defined when you are writing the program itself. In
certain cases you may require that when you are executing the program you want to give
the input or the initialization values in such a case we go in for constructors with
arguments. What ever the user gives during the execution of the program that will be
copied to the objects data members. So how is it done? What is the syntax for that? We
will see it using this example program.

#include<iostream.h>
class cal{
private:
int num1=num2,tot;
public:
cal(int.int);
void disp();
};

You are having the header file. You are having the class declaration CAL. You
are having the private data member .NUM1 NUM2 and TOT. So that there are three
integer variables. You are having the public access specified you are having the you are
having one function. You are having the constructor CAL which is the same as the class
name. This is the same as the class name so this is a constructor, it is having two integer
variables INT and INT.this is a constructor declaration. Next you are having next you are
having a function called DISP which does not return any value. You are closing the class
body. Now as I said earlier these two functions are only declared over here they are not
defined .So member functions inside a class can be declared inside the class but defined
outside the class or they can be declared or defined within a class. so when you are going
to define its body outside the class what is the syntax to be followed.
cal::cal(int x, int y)
{
num1=x:num2=y:tot=0:
}
cal::disp()
{tot=num1+num2:
cout<<" sum is" <<tot<<end;}
Now here if you see you are having the name of the class followed by two semi
colons followed by the function name followed by the function declaration you are
having the opening of the function and here you are initializing the values now what are
values that are initilized you are assigning this x value to the first variable the y value to
the second variable and this TOT you are assigning it to 0 so this x and y values are not
known during program compilation these are the two values that will be given by the user
later whenever during the execution the user gives these values they will simply be
copied to the integer variables and then you close this first function then again then again
the second function you are using the class name followed by these two semi colleens
followed by the function name here you dont have to mention the return type it is
sufficient if you mention simply the function name and if any arguments you have to
mention it that way The return type is not required when you define a function outside the
class here you are summing up this is just a program to add two numbers so you
summing up the two n umber num1 and num2 assigning it to tot variable and you are
displaying the sum now this two semi colons is called scope resolution operator as I
mentioned these two semi colons they have a technical term scope resolution operator so
what is this scope resolution operator this is used to access member functions and
constructors that are defined outside the boundary of the class like here were are having
only one class say we are having another class called cal1 cal2 cal3 cal4 how are we
going to know which function is defined outside the class to which class does it belong so
for us to know that this particular function belongs to this particular class we use a class
name followed by this scope resolution operator followed by the function name followed
by the parameters this scope resolution operator is used to link the function with the
particular class and it is the operator which denotes to the compiler that the function is
declared inside this class but its body is given here .so this makes more the program more
readable like the class definition becomes shorter and wherever you want a program
according to you users need he can legibly write it away from the class so makes the

program more neat it is denoted by two semi colleens one after the other so now we will
see how this main function calls these two functions .
Main()
{
int n1,n2
cout<"enter value 1";cin>>n1:
cout<<"enter vaue2":cin>>n2;
cal c(n1,n2);
cl.disp();
}
Every programs starts its execution from the main function followed by the
opening brace you are having two variables n1 and n2 you are entering the values for n1
and using the c operator your are getting the value your are asking the user to enter
second value for n2 then here you are calling the function the constructor cal c1 n1
comma n2 now as I said the constructor function is called only when the object is created
the way to create the object is the class name followed the object name so class name
followed the object name c1 here is the object as soon this object is created the
constructor will be called but the constructor is having two values so you have this two
values to the constructor so this n1 and n2 are the values which you have got from the
user so say if the user enter 5 and 10 these two values will be passed on to the constructor
so 5 and 10 will be going to this x and Y that will be allotted to num21 and num2 so the
num1 is having 5 and num2 is having 10 then c1 got DISP which adds it to values and
assigns it to tot and displays the value. So this is how the program is executed then finally
you have the out entering the first value 15 the second value 17 and the output 120 so this
is how constructors are declared member functions are declared they are defined outside
the class and they are accessed from the main function.
Destructor:
A destructor is nothing but for an object which has completed its work in the
program you are releasing the memory that is allotted to it that is you are destroying the
space you are destroying that object destroying that value and you are releasing the
memory space that is allocated to it so its complimentary to the constructor when there is
a constructor their should be a destructor because constructor allocates the memory so
you have to free the memory at sometime this is invoked when any instance of the class
ceases to exist constructor is invoked when ever you create a instance for a class destroy
is invoked when a class instance stops existing .destructor functions de-initializes the
objects when they are destroyed a program is relived of the task of freeing the memory
space that is allocated to a variable so from this itself you can identify that this is
something like the free function in C .So an constructors allocates an memory destructor
releases the memory . constructors allocates when an object is created destructor de
allocates when the object is destroyed so they both are complimentary to each other now
what are the character of these destructors first a destructors automatically invoked when
an object goes out of scope .when it goes out of out of view of the program out of the

need of the program the destructors is invoked this also has the same name as the class it
is prefixed with the tilde symbol I have given the symbol sign also A class can have only
one destructors this is also different from the constructor this also doe not specify any
return value and this also will be called explicitly now their are certain similarity and
certain differences between constructors and destructors .both have the same name as a
class they dot have return values but one program can have any number of constructors
but their can be only destructors in a program and secondly destructor are prefixed with
the tilde symbol they are called when a object ceases to exist and this de initializes the
memory allocated to an object now we will see how these destructors are included in the
program .
class cal{
private
int ni,n2;
pubic:

..cal()
{n1=n2=0:}};
you are having a class called CAL you are opening the body of the class you are
two private integer named as N1 and N2 you are having the public keyword when you
are having some function I just mentioned it using these dots it is just the skeletal vies
and here we are having the destructor declaration if you see this is having the same name
as the class CAL followed by opening and closing brackets prefixed with the tilde symbol
and here n1=n2=0 this is nothing but the body the destructor normally in destructors you
dont mentioned when the compiler sees the tilde symbol it will immediately understand
its a destructor and whatever variable is mentioned all the variables that are present in
the class will be de allocated and the memory will be released this is just an example that
is whatever value is assigned to n1 and n2 that is been destroyed and there are assigned
null values and then you close the body of the class so this is how the destructors are
declared inside a C++ program . Now in this case how can you explicitly cal the
destructor inside the main function.
Main{
cal ob1;

ob1,..ca();
}
Inside the main function here you create the object cal followed by the object
name and you do whatever operation you want to do using the object name the same
name way you access any other the member function you have to access the destructors
normally you use your object name followed by the dot operator followed by the function
here also the same thing we use the object OB1 followed by this dot operator followed by
the tiled symbol and the destructors name so this will automatically call the destructors
and destroy the variable that the object memory that was allocated and release the
memory for use by other programs you close the main function generally this explicit

invoking of the destructors normally not used by programmers who program usual kind
of applications its only used in advanced programming scenario used were one object
immediately after its completion of work in one particular scenario has to be used for
another scenario in that case you de allocate the memory allocated to it and you use it for
another place generally when object go out the scope the complier automatically calls the
destructor and releases the memory but when memory is highly needs to be used highly
efficiently u have to save the memory space in that case programmers invoke the
destructor explicitly generally this is not used by new programmers as we will as
programmers operate normal applications .

now life cycle of an object now we have seen about allocation of memory to an
object and de allocation of memory that is done to an object so when is memory to be
allocated when is memory to be destroyed for that we have to know when an object is
created how long does it exist and when does it actually cease to exist moreover the time
we dont the compiler when an object dies or goes out of scope it is automatically taken
up the complier.
class test
{
test()
{
cout<<"constructor invoked"<<endl;
}
so this program we have three objects each object has a different scope one object
is global in nature one object is local to a function and one object is local to a particular
block of statement so how does the complier identify when each object ceases to exist
and when each object starts to exists so here you are having this test class you are
opening the class body so this is nothing but a constructor because it is having the same
name as a Class name you are opening the constructor function and here you are not
having any initialization you are simply printing one line constructor invoke now this is
general not done in constructors constructor have to initialize values why I m using this
term is when you see the output u should be able to identify that the constructor was
invoked because our main aim of giving this program to know when the constructor is
invoked in a program so that is why constructor and destructor I have term likes this
constructor is invoked destructor is invoked that you will know when an object starts to
exist and when it ceases to exits so this constructor function I am displaying to the user
that the constructor has been invoked I am closing the constructor function.

~test()
{
cout<<"destructor invoked"<<end;
}};
test ob;

main()
{ cout<<"main begins"<<endl;
Then here I am declaring the destructor tilde symbol again the same name as the
class test inside that I am printing this statement destructor invoked and closing the
destructor function and am closing the class so if you see in this class function I am
having only two functions class test one is constructor and one is the destructor I am not
coding any another operation so in this should you would be able to identify when the
constructor is invoke when the destructor is invoked now always the complier starts
executing the program or compiling the program only from the main function so after it
sees the # include <iostream.h> it immediately search for the main function so if you see
here the class is ending here m creating one object test is the name of the class followed
by the object name the first object that I am creating is ob1 but how does the complier
indefinites after include <iostream.h> complier will come to this main function it will
search whether their any data between the class ending and the beginning of the main
function so when it sees it test ob1 it will identify that it is a outside the class because the
class is ended over here the class is already ended here main is starting only over here so
this object that is created is in between the class and the main function so it will assign a
global scope to that particular object global scope in the sense it is like the global variable
we have seen what is a global variables something that is available through out the entire
program so a compiler will assign global scope to this ob1 object that means this object
will continue to exits till the program completes its execution so this starting of the
constructor is here so the constructor is invoked whenever an object is created so when
this object is created by the user and the complier sees this particular statement in the
program it identify the it has to call the constructor.
~test()
{
cout<<"destructor invoked"<<end;
}}
test ob;
main()
{cout<<"main begins"<<endl;
Next it will go to the main function it will display main begins then again another object
is created this is having a function scope then some operations are done then see out in us
this is just some section of the program.

Test ob2;
.{
cout<<"inner section starts"<<endl;
Test ob3;
cout<<"inner section ends"<<endl;

}//destructor
cout<<"main ends"<<endl;
}

Then again another object is created which is having the bock scoped that is scope
of this particular object is only between these 2 statements. When you are closing the
function you are closing the main function and you are closing the entire program

now how is the out put seen for this particular program now the first time you
have the function constructor invoked so this constructor is invoked for this test ob1 be
so when this test ob1 given object is created it prints this particular data constructor
invoked the next statement is main begins after that again a constructor invoked so what
happens when begins how is this main begins coming as a next output after this first
particular object is created the complier enters the main function and it displays main
begins then immediately moves to the next statement which is nothing but creation of
second object so when the second object is created again the constructor is invoked that is
what is displayed as the next output constructor invoked after this constructor invoked
again it move to the inner part of the program inner sections starts again another test ob3
that is a creation of another object so when ever an object is created the constructor
automatically will, be invoked also again a constructor invoked statement followed by the
inner section ends and so inner section starts again a constructor invoked and again the
inner section ends so if you see that third constructor invoked is for this ob3 this scope
the ob3 is ends with this particular brace so as soon as this particular brace is encountered
by the complier. it called the destructor after this inner section ends immediately it will
display destructor invoked because that objects ob3 ceases to exits over there so you will
see how that takes place after inner sections ends destructor invoked this is for test ob3
then you have the function main ends because that it is the next statement seen by the
complier so this test ob2 scope closes with the main function so when it sees that the
main function gets over immediately the next destructor invoked will be displayed
destructor invoked will be displayed again and finally when the program ends the
destructor invoked further first object ob1 so here if you see when ever the object is
created the constructor statement is invoked and then the program proceeds as usual
thought out the normal function and when ever the brace the brace is the most important
part of this entire program based on the closing brace and the opening brace only the life
cycle of an object is determined if an object is having a global it is visible during the
entire program if this is inside the main function then the main function ends the objects
ceases to exist if it inside the bock of statement like if loop or for loop or while loop once
the loop gets over its life cease to exist so according to that only constructor invoked may
begins inner sections starts and all these statements have been so this is the life cycle of
an object is determined by the complier soon that is the reason when indicates the body of
the looping statement both of the main function body of the class it is highly essential that
we are extremely careful because when we use a constructor these function they allocate
and de allocate memory accordingly if we misuse the brace memory will be de allocated

when we actually require the memory so we have to be careful that we denote the life
cycle of an object probably to the complier
so I have told about the global scope function scope and blog scope this we have
already seen in the c language scope defines the context of the variable that is were it
may be accessed were it is actually alive three types of scopes exist in c++ one is the file
scope local scope and class scope so file scope is nothing but when we using a fie
systems in c you create one c fie in side that whatever variables using only as long as the
fie is open u can access it once the file is closed the scope is gone similarly local scope is
local to a particular function or to a block of statements class is as long as the class is
existing the variables and numbers will have their scope once the class is closed and not
in execution not in us e the class variables will be losing their memory .so these are the
two types of scope that are available in C++.

You might also like