Constructors
And Destructors
UNIT — II
2
Constructors
A constructor is a special type of member function of a
class which initializes objects of a class. In C++, Constructor
is automatically called when object(instance of class)
create. It is special member function of the class because it
does not have any return type.It is used to initialize the
data members of new objects generally. The constructor in
C++ has the same name as the class or structure.
Constructor is invoked at the time of object creation. It
constructs the values i.e. provides data for the object which
is why it is known as constructors.
For example : class Wall { public: // create a constructor Wall()
{ // code } };
3 3
Why do we need Constructors?
The main purpose of the class constructor in C++ programming is to
construct an object of the class. In other word, it is used to initialize all
class data members. ... Note that if we don't write a constructor in the
class, compiler will provide default constructor in C++
programming.Constructors are methods that are automatically executed
every time you create an object. The purpose of a constructor is to
construct an object and assign values to the object's members. A
constructor takes the same name as the class to which it belongs, and
does not return any values.
The main purpose of the class constructor in C++ programming is to construct an
object of the class. In other word, it is used to initialize all class data members.
4
Initialization using constructors
Initializer List is used in initializing the data members
of a class. The list of members to be initialized is
indicated with constructor as a comma-separated list
followed by a colon.
❏ There are two ways to initialize a class object:
❏ Using a parenthesized expression list. The compiler
calls the constructor of the class using this list as the
constructor's argument list.
❏ Using a single initialization value and the = operator.
“
5
Types of constructors
❏ There are three types of constructor in C++.
Default Copy
Parameterized
Constructor
6
Default Constructors
A default constructor is a constructor that either has no
parameters, or if it has parameters, all the parameters
have default values. If no user-defined constructor exists
for a class A and one is needed, the compiler implicitly
declares a default parameterless constructor A::A() .
A constructor is a special member function of a class
which initializes objects of a class. In C++, constructor is
automatically called when object of a class is created. By
default, constructors are defined in public section of
class.
7
7
Parameterized Constructors
There are many methods in C++. But parameterized
constructor in C++ are some special types of method
which gets instantiated as soon as an object is created.
Therefore, there are two types of constructors defined in
C++ namely default constructor, Parameterized
constructor. There is a minute difference between default
constructor and Parameterized constructor. The default
constructor is a type of constructor which has no
arguments but yes object instantiation is performed there
also. On the other hand, as the name suggests
Parameterized constructor is a special type of constructor
where an object is created, and further parameters are
passed to distinct objects.
8
8
8
Copy Constructors
A constructor in C++ is used to initialise an object. A copy
constructor is a member function of a class that initialises
an object with an existing object of the same class. In
other words, it creates an exact copy of an already
existing object and stores it into a new object.
Copy Constructor is of two types:
❏ Default Copy constructor : The compiler defines the
default copy constructor. If the user defines no copy
constructor, compiler supplies its constructor.
❏ User Defined constructor : The programmer defines
the user-defined constructor.
9
9
9
9
Constructor Overloading
In C++, We can have more than one constructor in a class
with same name, as long as each has a different list of
arguments.This concept is known as Constructor
Overloading and is quite similar to Function overloading.
Overloaded constructors essentially have the same name
(exact name of the class) and differ by number and type
of arguments. A constructor is called depending upon the
number and type of arguments passed. While creating the
object, arguments must be passed to let compiler know,
which constructor needs to be called.
10
10
10
10
Constructor Overloading
❏ Overloaded constructors essentially have the same
name (exact name of the class) and differ by number
and type of arguments.
❏ A constructor is called depending upon the number
and type of arguments passed.
❏ While creating the object, arguments must be passed
to let compiler know, which constructor needs to be
called.
❏ While creating the object, arguments must be passed
to let compiler know, which constructor needs to be
called.
11
11
11
11
11
Default value to parameters
A default argument is a value provided in a function
declaration that is automatically assigned by the compiler
if the caller of the function doesn't provide a value for the
argument with a default value. In case any value is passed
the default value is overridden.
❏ Default Parameters
❏ function myFunction(x, y) {
❏ if (y === undefined) { y = 2;
❏ }
❏ }
12
12
12
12
12
Default value to parameters
❏ If a function with default arguments is called without
passing arguments, then the default parameters are
used
❏ You can also use a default parameter value, by using
the equals sign (=).
❏ If we call the function without an argument, it uses
the default value ("Norway"):
The default constructor with argument has a default
parameter x, which has been assigned a value of 0.
13
13
13
13
13
13
Destructors
Destructor is an instance member function which is
invoked automatically whenever an object is going to be
destroyed. Meaning, a destructor is the last function that
is going to be called before an object is destroyed.
The thing is to be noted here, if the object is created by
using new or the constructor uses new to allocate
memory which resides in the heap memory or the free
store, the destructor should use delete to free the
memory.
14
14
14
14
14
14
14
Properties of Destructors
❏ Destructor function is automatically invoked
when the objects are destroyed.
❏ It cannot be declared static or const.
❏ The destructor does not have arguments.
❏ It has no return type not even void.
❏ An object of a class with a Destructor cannot
become a member of the union.
❏ A destructor should be declared in the public
section of the class.
15
15
15
15
15
15
15
15
When is Destructor Called ?
A destructor function is called automatically when
the object goes out of scope:
❏ The function ends.
❏ The program ends.
❏ A block containing local variables ends .
❏ A delete operator is called.
16
16
16
16
16
16
16
16
16
Hierarchy of console stream classes
Stream classes are set of classes, whose functionality
depends on console file operations. The stream classes
are declared in header file “iostream.h”. It is mandatory
for a programmer to include this header file, whenever a
program is written using the functions supported by these
stream classes.
17 17
17
17
17
17
17
17
17
17
17
17
17
17
17
17
17
17
Hierarchy of console stream classes
From the above hierarchical structure it can be inferred
that,
❏ (i) ios is the parent class.
❏ (ii) istream, ostream are child classes.
❏ (iii) iostream buffer is a member variable object of
ios.
❏ (iv) The iostream class is a child class of both istream
class and ostream class.
The other streams include classes istream_withassign,
Ostream_withassign and iostream_withassign. They are
used to append the required assignment operators.
18
18 18
18
18
18
18
18
18
18
18
18
18
18
18
18
18
18
18
Hierarchy of console stream classes
Types of Stream Classes:
The different stream classes include,
(a) iso.
(b) istream.
19
19
19 19
19
19
19
19
19
19
19
19
19
19
19
19
19
19
19
19
Hierarchy of console stream classes
(c) ostream.
(d) iostream.
(e) istream_withassign.
(f) ostream_withassign.
(g) iostream_withassign.
20
20
20
20 20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
20
Unformatted input output
operations
Unformatted console input/output functions are used
for performing input/output operations at console and
the resulting data is left unformatted and
untransformed i.e. it is left in its raw and original form.
The printed data with default setting by the I/O
function of the language is known as unformatted
data. It is the basic form of input/output and transfers
the internal binary representation of the data directly
between memory and the file. For example, in cin
statement it asks for a number while executing.
❏ Syntax :
(cin >> var1 >> var2 >> …. >> var_n;)
❏ Here, var1, var2, ……, varn are the variable
names that are declared already.
❏ The input data must be separated by white
space characters and the data type of user
input must be similar to the data types of the
variables which are declared in the program.
21
21
21
21 21
21
21
21
21
21
21
21
21
21
21
21
21
21
21
21
21
Unformatted input output
operations
22
22
S 22
22
22
22
22
22
22
22
22
22
22
22
22
22
22
22
Unformatted input output
operations
❏ The operator >> reads the data character by
character and assigns it to the indicated location.
❏ Reading of variables terminates when white space
occurs or character type occurs that does not
match the destination type.
❏ Unformatted I/O functions are used only for
character data type or character array/string and
cannot be used for any other datatype. These
functions are used to read single input from the
user at the console and it allows to display the
value at the console.
23
23
23
23
23
23 23
23
23
23
23
23
23
23
23
23
23
23
23
23
23
23
23
Formatted input output
operations
C++ helps you to format the I/O operations
like determining the number of digits to be
displayed after the decimal point, specifying
number base etc.
❏ For Example :If we want to add + sign as the
prefix of out output, we can use the formatting to
do so:
❏ stream.setf(ios::showpos)
❏ If input=100, output will be +100
24
24
24
24
24
24 24
24
24
24
24
24
24
24
24
24
24
24
24
24
24
24
24
Formatted input output
operations
❏ For Example : If we want to add trailing zeros in
out output to be shown when needed using the
formatting:
❏ stream.setf(ios::showpoint)
❏ If input=100.0, output will be 100.000
Note: Here, stream is referred to the streams defined in
c++ like cin, cout, cerr, clog.
25
25
25
25
25
25 25
25
25
25
25
25
25
25
25
25
25
25
25
25
25
25
25
Formatted input output
operations
❏ There are two ways to do so:
❏ Using the ios class or various ios member
functions.
❏ Using manipulators(special functions)
❏ Formatting using the ios members: The stream has
the format flags that control the way of formatting
it means Using this setf function, we can set the
flags, which allow us to display a value in a
particular format.
26
26
26
26
26
26 26
26
26
26
26
26
26
26
26
26
26
26
26
26
26
26
26
Formatted input output
operations
❏ Formatting using the ios members: The ios class
declares a bitmask enumeration called fmtflags in
which the values(showbase, showpoint, oct, hex
etc) are defined. These values are used to set or
clear the format flags.
❏ Few standard ios class functions are:
❏ width(): The width method is used to set the
required field width. The output will be displayed in
the given width
❏ precision(): The precision method is used to set the
number of the decimal point to a float value
27
27
27
27
27
27 27
27
27
27
27
27
27
27
27
27
27
27
27
27
27
27
27
Formatted input output
operations
❏ Few standard ios class functions are:
❏ fill(): The fill method is used to set a character to fill
in the blank space of a field
❏ setf(): The setf method is used to set various flags
for formatting output
❏ unsetf(): The unsetf method is used To remove the
flag setting
28
28
28
28
28
28 28
28
28
28
28
28
28
28
28
28
28
28
28
28
28
28
28
Formatted input output
operations
❏ Formatting using Manipulators : The second way
you can alter the format parameters of a stream is
through the use of special functions called
manipulators that can be included in an I/O
expression.
❏ The standard manipulators are shown below:
❏ Boolalpha: The boolalpha manipulator of stream
manipulators in C++ is used to turn on bool alpha
flag
❏ Dec: The dec manipulator of stream manipulators
in C++ is used to turn on the dec flag
29
29
29
29
29
29 29
29
29
29
29
29
29
29
29
29
29
29
29
29
29
29
29
Formatted input output
operations
❏ The standard manipulators are shown below:
❏ endl: The endl manipulator of stream manipulators
in C++ is used to Output a newline character.
❏ and: The and manipulator of stream manipulators
in C++ is used to Flush the stream
❏ ends: The ends manipulator of stream manipulators
in C++ is used to Output a null
❏ fixed: The fixed manipulator of stream
manipulators in C++ is used to Turns on the fixed
flag.
Thanks !

Constructors or destructors unit(II).pdf

  • 1.
  • 2.
    2 Constructors A constructor isa special type of member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object(instance of class) create. It is special member function of the class because it does not have any return type.It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object which is why it is known as constructors. For example : class Wall { public: // create a constructor Wall() { // code } };
  • 3.
    3 3 Why dowe need Constructors? The main purpose of the class constructor in C++ programming is to construct an object of the class. In other word, it is used to initialize all class data members. ... Note that if we don't write a constructor in the class, compiler will provide default constructor in C++ programming.Constructors are methods that are automatically executed every time you create an object. The purpose of a constructor is to construct an object and assign values to the object's members. A constructor takes the same name as the class to which it belongs, and does not return any values. The main purpose of the class constructor in C++ programming is to construct an object of the class. In other word, it is used to initialize all class data members.
  • 4.
    4 Initialization using constructors InitializerList is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. ❏ There are two ways to initialize a class object: ❏ Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. ❏ Using a single initialization value and the = operator.
  • 5.
    “ 5 Types of constructors ❏There are three types of constructor in C++. Default Copy Parameterized Constructor
  • 6.
    6 Default Constructors A defaultconstructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() . A constructor is a special member function of a class which initializes objects of a class. In C++, constructor is automatically called when object of a class is created. By default, constructors are defined in public section of class.
  • 7.
    7 7 Parameterized Constructors There aremany methods in C++. But parameterized constructor in C++ are some special types of method which gets instantiated as soon as an object is created. Therefore, there are two types of constructors defined in C++ namely default constructor, Parameterized constructor. There is a minute difference between default constructor and Parameterized constructor. The default constructor is a type of constructor which has no arguments but yes object instantiation is performed there also. On the other hand, as the name suggests Parameterized constructor is a special type of constructor where an object is created, and further parameters are passed to distinct objects.
  • 8.
    8 8 8 Copy Constructors A constructorin C++ is used to initialise an object. A copy constructor is a member function of a class that initialises an object with an existing object of the same class. In other words, it creates an exact copy of an already existing object and stores it into a new object. Copy Constructor is of two types: ❏ Default Copy constructor : The compiler defines the default copy constructor. If the user defines no copy constructor, compiler supplies its constructor. ❏ User Defined constructor : The programmer defines the user-defined constructor.
  • 9.
    9 9 9 9 Constructor Overloading In C++,We can have more than one constructor in a class with same name, as long as each has a different list of arguments.This concept is known as Constructor Overloading and is quite similar to Function overloading. Overloaded constructors essentially have the same name (exact name of the class) and differ by number and type of arguments. A constructor is called depending upon the number and type of arguments passed. While creating the object, arguments must be passed to let compiler know, which constructor needs to be called.
  • 10.
    10 10 10 10 Constructor Overloading ❏ Overloadedconstructors essentially have the same name (exact name of the class) and differ by number and type of arguments. ❏ A constructor is called depending upon the number and type of arguments passed. ❏ While creating the object, arguments must be passed to let compiler know, which constructor needs to be called. ❏ While creating the object, arguments must be passed to let compiler know, which constructor needs to be called.
  • 11.
    11 11 11 11 11 Default value toparameters A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the caller of the function doesn't provide a value for the argument with a default value. In case any value is passed the default value is overridden. ❏ Default Parameters ❏ function myFunction(x, y) { ❏ if (y === undefined) { y = 2; ❏ } ❏ }
  • 12.
    12 12 12 12 12 Default value toparameters ❏ If a function with default arguments is called without passing arguments, then the default parameters are used ❏ You can also use a default parameter value, by using the equals sign (=). ❏ If we call the function without an argument, it uses the default value ("Norway"): The default constructor with argument has a default parameter x, which has been assigned a value of 0.
  • 13.
    13 13 13 13 13 13 Destructors Destructor is aninstance member function which is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed. The thing is to be noted here, if the object is created by using new or the constructor uses new to allocate memory which resides in the heap memory or the free store, the destructor should use delete to free the memory.
  • 14.
    14 14 14 14 14 14 14 Properties of Destructors ❏Destructor function is automatically invoked when the objects are destroyed. ❏ It cannot be declared static or const. ❏ The destructor does not have arguments. ❏ It has no return type not even void. ❏ An object of a class with a Destructor cannot become a member of the union. ❏ A destructor should be declared in the public section of the class.
  • 15.
    15 15 15 15 15 15 15 15 When is DestructorCalled ? A destructor function is called automatically when the object goes out of scope: ❏ The function ends. ❏ The program ends. ❏ A block containing local variables ends . ❏ A delete operator is called.
  • 16.
    16 16 16 16 16 16 16 16 16 Hierarchy of consolestream classes Stream classes are set of classes, whose functionality depends on console file operations. The stream classes are declared in header file “iostream.h”. It is mandatory for a programmer to include this header file, whenever a program is written using the functions supported by these stream classes.
  • 17.
    17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 Hierarchy ofconsole stream classes From the above hierarchical structure it can be inferred that, ❏ (i) ios is the parent class. ❏ (ii) istream, ostream are child classes. ❏ (iii) iostream buffer is a member variable object of ios. ❏ (iv) The iostream class is a child class of both istream class and ostream class. The other streams include classes istream_withassign, Ostream_withassign and iostream_withassign. They are used to append the required assignment operators.
  • 18.
    18 18 18 18 18 18 18 18 18 18 18 18 18 18 18 18 18 18 18 Hierarchy ofconsole stream classes Types of Stream Classes: The different stream classes include, (a) iso. (b) istream.
  • 19.
    19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 Hierarchy ofconsole stream classes (c) ostream. (d) iostream. (e) istream_withassign. (f) ostream_withassign. (g) iostream_withassign.
  • 20.
    20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 Unformatted inputoutput operations Unformatted console input/output functions are used for performing input/output operations at console and the resulting data is left unformatted and untransformed i.e. it is left in its raw and original form. The printed data with default setting by the I/O function of the language is known as unformatted data. It is the basic form of input/output and transfers the internal binary representation of the data directly between memory and the file. For example, in cin statement it asks for a number while executing.
  • 21.
    ❏ Syntax : (cin>> var1 >> var2 >> …. >> var_n;) ❏ Here, var1, var2, ……, varn are the variable names that are declared already. ❏ The input data must be separated by white space characters and the data type of user input must be similar to the data types of the variables which are declared in the program. 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 Unformatted input output operations
  • 22.
    22 22 S 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 Unformatted inputoutput operations ❏ The operator >> reads the data character by character and assigns it to the indicated location. ❏ Reading of variables terminates when white space occurs or character type occurs that does not match the destination type. ❏ Unformatted I/O functions are used only for character data type or character array/string and cannot be used for any other datatype. These functions are used to read single input from the user at the console and it allows to display the value at the console.
  • 23.
    23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 Formatted inputoutput operations C++ helps you to format the I/O operations like determining the number of digits to be displayed after the decimal point, specifying number base etc. ❏ For Example :If we want to add + sign as the prefix of out output, we can use the formatting to do so: ❏ stream.setf(ios::showpos) ❏ If input=100, output will be +100
  • 24.
    24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 Formatted inputoutput operations ❏ For Example : If we want to add trailing zeros in out output to be shown when needed using the formatting: ❏ stream.setf(ios::showpoint) ❏ If input=100.0, output will be 100.000 Note: Here, stream is referred to the streams defined in c++ like cin, cout, cerr, clog.
  • 25.
    25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 Formatted inputoutput operations ❏ There are two ways to do so: ❏ Using the ios class or various ios member functions. ❏ Using manipulators(special functions) ❏ Formatting using the ios members: The stream has the format flags that control the way of formatting it means Using this setf function, we can set the flags, which allow us to display a value in a particular format.
  • 26.
    26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 Formatted inputoutput operations ❏ Formatting using the ios members: The ios class declares a bitmask enumeration called fmtflags in which the values(showbase, showpoint, oct, hex etc) are defined. These values are used to set or clear the format flags. ❏ Few standard ios class functions are: ❏ width(): The width method is used to set the required field width. The output will be displayed in the given width ❏ precision(): The precision method is used to set the number of the decimal point to a float value
  • 27.
    27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 Formatted inputoutput operations ❏ Few standard ios class functions are: ❏ fill(): The fill method is used to set a character to fill in the blank space of a field ❏ setf(): The setf method is used to set various flags for formatting output ❏ unsetf(): The unsetf method is used To remove the flag setting
  • 28.
    28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 Formatted inputoutput operations ❏ Formatting using Manipulators : The second way you can alter the format parameters of a stream is through the use of special functions called manipulators that can be included in an I/O expression. ❏ The standard manipulators are shown below: ❏ Boolalpha: The boolalpha manipulator of stream manipulators in C++ is used to turn on bool alpha flag ❏ Dec: The dec manipulator of stream manipulators in C++ is used to turn on the dec flag
  • 29.
    29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 Formatted inputoutput operations ❏ The standard manipulators are shown below: ❏ endl: The endl manipulator of stream manipulators in C++ is used to Output a newline character. ❏ and: The and manipulator of stream manipulators in C++ is used to Flush the stream ❏ ends: The ends manipulator of stream manipulators in C++ is used to Output a null ❏ fixed: The fixed manipulator of stream manipulators in C++ is used to Turns on the fixed flag.
  • 30.