- Constructors are special member functions that are used to initialize objects of a class. They are automatically called when an object is created.
- There are different types of constructors including default, parameterized, and copy constructors. Default constructors take no parameters while parameterized constructors allow passing initial values.
- Constructors can be explicitly or implicitly called. Implicit calls are made when an object is declared while explicit calls directly call the constructor. Constructors ensure objects are properly initialized.
1. CONSTRUCTORS
AND
DESTRUCTORS
CONSTRUCTORS
AND
DESTRUCTORS
When you define a class, it does not create
objects of that class, rather it only specifies
what type of information the objects of this
class will be containing. This chapter discuss
the means for creating (initializing) and
disposing of Objects of a class. C++ provides
mechanism for initializing an objects when it is
created by means of a constructor; same way
when an object is no more needed, we can
scrap it off by means of a destructor.
2. Constructor. A constructor is special member function and has the
same name of that class. It will automatically called when an object is created.
And its primary job is to initialize an object. Constructors and destructors have
no return type.
class student
{
int roll, marks;
public:
student()
{
roll = marks = 0;
}
};
main()
{
student a;
}
REMEMBER FOLLOWING
Constructors must have the same name of class.
It will automatically called when an object is
created.
its primary job is to initialize an object.
Constructors have no return type.
3. Initialization of Structure Objects. By default, all members of a
‘struct‘ object is public. So members of ‘struct’ can access from anywhere.
# include <iostream.h>
# include <conio.h>
struct length
{
int feet, inch;
public:
void out()
{
cout << "nnFeet = " << feet << " and Inch = " << inch;
}
};
main() {
length a={10, 8}, b={5,7};
a.out();
b.out();
getch();
}
In ‘struct’ members are public by
default. By this reason objects of
structure can be initialized at the time
of their declaration.
Feet and inch are public, main can
access these variables and initialize.
a.feet = 10, a.inch = 8 and b.feet = 5,
b.inch = 7.
This does not
work for private
data members.
By default all
members of a
class are private,
this type of
initialization is
not applicable
for class objects.
4. # include <iostream.h>
# include <conio.h>
class student
{
private:
int roll_no;
Float marks;
public:
void out()
{
cout << "nnRoll No = " << roll_no;
cout << " and Marks = " << marks;
}
};
main()
{
student a;
a.out();
getch();
}
Output
Roll No = 100 and Marks = 78
# include <iostream.h>
# include <conio.h>
class student
{
private:
int roll_no;
Float marks;
public:
void init() { roll_no = 100; marks = 78; }
void out()
{
cout << "nnRoll No = " << roll_no;
cout << " and Marks = " << marks;
}
};
main()
{
student a;
………
a.out();
getch();
}
Output
Roll No = -5261 and Marks = -627778
init() will initialize roll_no = 100
and marks = 78.
The responsibility of initialization lies
solely with the programmer. So init()
will explicitly invoked by the
programmer.
User forget to initialize
data by invoking init();
So the out will be
grabage.
void init() { roll_no=100; marks = 78; }
a.init(); a.init();
5. # include <iostream.h>
# include <conio.h>
class length
{
int feet, inch;
public:
void out()
{
cout << "nnFeet = " << feet;
cout << " and Inch = " << inch;
}
};
main()
{
a.out();
getch();
}
Output
Feet = 0 and Inch = 0
Constructors must have
the same name of class.
length() { feet = inch = 0; }
length a;
You can define a constructor under
private or protected sections. If the
constructor is private/protected, you
can’t create an object of that class in
a non member function because of
private/protected constructor is not
available to a non member functions.
Generally a Constructor should
be defined in public section of
the class. So that its objects can
be created in any function.
Every time an object is created,
the constructor will automatically
invok and initialize object with
pre-specified values.
6. class X
{
int i;
public:
void getval() { cin >> i; }
void print() { cout << “I = “ << I; }
void check();
friend void ABC();
};
void X :: check()
{
X ob1j;
}
void ABC()
{
X obj2;
}
void main()
{
X obj3;
}
Valid !.
check() is member of class X. So
it can access the Constructor of X
even if it is private.
Valid !.
ABC() is a friend function of X.
Friend Functions can access
private members.
Invalid !.
main() can’t access the constructor of
class X. because X() is defined in
private section of class X.
X () { I = 0; }
Constructor X() is defined in
private section of the class. It
can’t be accessed from outside of
class X.
A class having no
public constructors is
a private class. Only
the member & friend
functions may
declare objects of
that class.
7. Types of Constructors. A class have multiple constructors, for various situations.
All constructors has same name. Multiple functions with a common name are called
function overloading. Names of overloaded constructors are Default Constructors,
Parameterized Constructors and Copy Constructors.
Default Constructors. A constructor that accept no parameter is called
default Constructors. If a class has no explicit constructor defined, the compiler will
supply a default constructor. This constructor is an inline public member of the class.
The default constructor provided by the compiler does not do anything specific, it
allocate memory to data members.
Parameterized Constructors. Constructor that accepts parameters for its
invocation is known as parameterized constructor. A parameterized constructor also
have default arguments. A constructor with default arguments is equivalent to a
default constructor. The parameterized constructors sometimes also called regular
constructors, it allow us to initialize various data members with different values.
Copy Constructors. A copy constructor is a constructor of the form
class_name (class_name &). The compiler will use the copy constructor whenever
you initialize an object using values of another instance of same type.
8. Default Constructors. A constructor that accept no parameter is called default Constructors.
# include <iostream.h>
class length
{
int f, i;
public:
void out()
{
cout << “ Feet = “ << f << “ & inch=“<<i;
}
};
main()
{
length a;
a.out();
}
Every time an object is
created, the constructor
will automatically invoked.
And will initialize an object
as on as it is created.
length ( )
{
f = i = 0;
}
A constructor
that accept no
parameter is
called default
Constructors. Constructor
defined by the
user is also called
Explicit
Constructor.
9. OUTPUT
Feet = -44 & inch=-98
# include <iostream.h>
class length
{
int f, I;
public: //It has NO CONSTRUCTOR
void out()
{
cout<<“Feet=“<<f<<“ & inch=“<<i;
}
};
main()
{
length a;
a.out();
}
If a class has no constructor,
the compiler will supply a
default constructor. The
constructor provided by
the compiler is called
Implicit Constructor. This
constructor is an inline
public member of the class.
The default constructor
provided by the compiler
does not do anything
specific, it allocate memory
to data members.
length ()
{
Allocate 2 bytes memory for f (feet)
Allocate ,, ,, ,, for I (inch)
and they will not initialize.
}
Ouput will be garbage
values.
Implicit Constructor. The constructor provided by the compiler is called Implicit
Constructor.
10. Parameterized Constructor. Constructor that accepts parameters for its
invocation is known as Parameterized Constructor or Regular Constructors.
# include <iostream.h>
class square
{
int val;
public:
void square_out()
{
cout<<“Square is “<<val*val;
}
};
main()
{
square x=5,
y=6;
a.square_out();
a.square_out();
}
square(int arg)
{ val = arg; }
Constructor accepts parameter(arg) and its
value will be assigned to the member data.
val = arg;
5
6
When object y is created,
the value ‘5’ is passed, and
the data member ‘val’ will be
initialized with this
argument. i.e. val = 5.
When object y is created, the
value ‘6’ is passed, and the
data member ‘val’ will be
initialized with this argument.
Constructor will be invoked
twice with the values 5 & 6
respectively.
OUTPUT
Square is 25
Square is 36
11. Function Overloading. Defining multiple functions with the same name is
known as Function Overloading. Each definition is distinguished by their signature.
The arguments List of a function is known as ‘Function Signature’. A function name
having several definitions that are differential by the number or type of their
arguments is called Function Overloading.
int sum(int a, int b)
{
return a+b;
}
float sum(float a, float b)
{
return a+b;
}
int sum(int a, int b, int c)
{
return a+b+c;
}
float sum(int a, float b)
{
return a+b;
}
int main()
{
int a = 10, b = 20, c = 30;
float d = 3.5, e = 2.75;
cout << sum(a,b);
cout << sum(d,e);
cout << sum(a, b, c);
cout << sum(a, d);
}
Constructors can also be Overloaded. All constructors have the same name, but
they differ in function signature. Constructors can be of 3 types. Default
Constructors, Parameterized Constructors and Copy Constructors.
12. # include <iostream.h>
class length
{
int feet, inch;
public:
void out()
{ cout<<“Feet=“<<feet<<“ & inch=“<<inch; }
};
main()
{
length a(5,8);
length b;
a.out(); b.out();
}
A constructor that
accepts parameters
is called a
Parameterised
Constructor.
length ()
{
feet = inch = 0;
}
length (int arg1, int arg2 )
{
feet = arg1; inch = arg2;
}
85
A constructor that do not
accept any parameter is
called a Default
Constructor.
a :: feet = 5 ( a.feet )
a :: inch = 8 ( a.inch )
b :: feet = 0 ( b.feet )
b :: inch = 0 ( b.inch )
Both Constructors have the same
name. But the No of their
arguments are different.
13. Default Arguments. C++ allows a function to have parameters with initial values
when the arguments corresponding to those parameters are not specified in the function
call statement. We can assign a value for the missing argument. Such arguments are
called ‘Default Arguments’. If a function contains more parameters than are required for
its common usage, you need specify the only the arguments that are necessary to the
exact situation missing arguments will gets default values.
# include <iostream.h>
int sum(int a1, int a2, int a3 = 0)
{
return a1 + a2 + a3;
}
main()
{
cout << sum(10,20);
cout << sum(10,20,30);
}
10 20
# include <iostream.h>
int sum(int a1, int a2, int a3 = 0, int a4=0)
{
return a1 + a2 + a3;
}
main()
{
cout << “nSum is “ << sum(10,20,30,40);
}
= 0
First 2 arguments are are compulsory. a3 and a4
becomes ‘0’ if they are omitted.
cout << “nSum is “ << sum(10,20);
You want to get sum of only 2 nos 10 and
20. Remaining a3 and a4 becomes ‘0’
You want to get sum of only 2 nos
10 and 20. Remaining a3 becomes
‘0’
cout << “nSum is “ << sum(10,20,30);
You want to get sum of 3 nos 10,20
and 30. Remaining a4 becomes ‘0’.
14. Constructor With Default Arguments. Just like any other function, a
parameterized constructor can also have default arguments. Constructor with
default arguments is equivalent to ‘Default Constructor’.
# include <iostream.h>
class length
{
int feet, inch;
public:
length()
{ feet = inch = 0; }
length (int a1 = 0, int a2 = 0)
{ ieet = a1; inch = a2; }
};
main()
{
length l1;
length l2(10,5);
}
There are no Arguments. So a
‘Default Constructor’.
There are Arguments. So
a ‘Parameterized
Constructor’. If the
arguments are omitted,
then they will get ‘Default
values. So it can be
invoked without any
arguments. Since the
arguments are not
necessary, it is just like a
‘Default Constructor’.
Error.
Ambiguit
y will
occur.
15. Significance of Default Constructor. The default constructor is very useful in the
following situations.
When you want to create objects without having initial
values.
When you want to initialize objects with specific initial
values.
When you want to create array of objects. You can’t create
an array of objects unless the class has a default constructor.
Parameterized constructor will hide implicit default Constructor.
There are 2 types of default constructors.
• Explicit default Constructors. It is the default constructor defined by the User.
• Implicit default constructor. If a class has no explicit constructors, the
compiler will supply a default constructor. such constructors are called Implicit
default Constructors.
16. # include <iostream.h>
class length
{
int feet, inch;
public:
void out()
{ cout<<“Feet=“<<feet<<“ & Inch=“<<inch; }
};
main()
{
length a;
a.out();
}
length ()
{
}
Example of Default Constructor.
# include <iostream.h>
class length
{
int feet, inch;
public:
void out()
{cout<<“Feet=“<<feet<<“&
Inch=“<<inch;}
};
main()
{
length a;
a.out();
}
length ()
{
feet = inch = 0;
}
Create objects without having initial values.
Output
Feet = -8347 & Inch = -737
Create objects with initial value zero.
Output
Feet = 0 & Inch = 0
17. # include <iostream.h>
# include <conio.h>
class length
{
int feet,inch;
public:
void out()
{ cout << "Feet = " << feet << " & Inch = " << inch; }
};
main()
{
length a(5,8);
Length b;
length x[3] ;
a.out();
x[0].out(); x[1].out(); x[2].out();
getch();
}
Error !
Here object ‘b’ and array ‘x’
are declared without initial
values. A constructor
without parameter is not
available. This situation
can’t be tackled.
You can’t create an array of objects unless the class has a default constructor.
length(int arg1, int arg2)
{
feet = arg1; inch = arg2;
}
5 8
There is no default
constructor.
What Can I Do
?
OK. Constructor accepts
parameter is avilable.
18. # include <iostream.h>
class length
{
int feet, inch;
public:
};
main()
{
length a[3];
length b(5,8);
}
length()
{
cout << “nDefault Constructor being called”;
}
length(int arg1, int arg2)
{
feet = arg1; inch = arg2;
cout << “nParameterized Constructor called”;
}
Creating Array of Objects.
Output
Default Constructor being called
Default Constructor being called
Default Constructor being called
Parameterized Constructor called5 8
19. Invocation of Constructors.
Constructors are useful to provide initial values of various data elements of
different object. Initial values are given when an object being declare.
Constructor will receive these values and assigned in data members.
Constructors will be invoked in following 2 ways.
Implicit call to the constructor. By implicit call, the constructor is invoked
even its name has not been mentioned. This method is shorter, easy and looks
better.
Explicit call to the constructor. By explicit call, the name of the
constructor is explicitly written to invoke the constructor.
int main()
{
length a; the constructor is invoked even its name has not been mentioned.
length b(5,8); constructor is invoked even its name has not been mentioned.
length c = length(8,5); the constructor will be explicitly called by giving the
name of the constructor.
}
Explicit Calling.
20. # include <iostream.h>
class length
{
int feet, inch;
public:
void out()
{ cout << "nnFeet = " << feet << " and Inch = " << inch; }
};
int main()
{
length a(3,7);
length b =
length x[3] = { };
x[0].out(); x[1].out(); x[2].out();
getch();
}
ExampleofExplicitInvocation.
length(int arg1, int arg2)
{
feet = arg1; inch = arg2;
}
length(2,3), length(5,8), length(7,3)
length(5,8);5 8
the constructor is invoked
without mention its name.
Implicit Invocation.
Constructor is invoked
using its name. Explicit
Invocation.
21. Temporary Instance. Temporary instance is the one that lies in memory
as long as it is being used or referenced in an expression and after this it dies.
Temporary instances are anonymous i.e. they do not bear a name. An explicit call to
the constructor lets you create a temporary instance. Temporary instances are
deleted when they are no longer referenced.
# include <iostream.h>
class length
{
int mtr, cm;
public:
length(int m, int c)
{ mtr = m; cm = c; }
int total_cm()
{ return (mtr*100)+cm; }
};
main()
{
cout << "n2 mtr and 50 cm = " << << " cm. ";
}
502
250
Creating a anonymous instance of
class length, having 2 mtrs and 50 cm.
It will die after invoking total_cm(),
that will return (2*100)+50
After creating
anonymous
instance, invok
total_cm(), that will
return (2*100)+50
length(2,50).total_cm()
22. 11:55:20 AM
Constructors and primitive types. Primitive type also have their own
constructors. When no values are provided, they use their default constructors.
But when you provide initial values, the newly created instance is initialized with
the provided value.
int a,b,c;
int i=3, j=4, k(5);
float x(4.19), y(3.22);
Situations when constructors are called.
1) When you create an instance of a class.
main()
{
length a; // Invoke Default Constructor
length b(5,10); // Implicit Invocation of Parameterized Constructor.
length c = length(5,10); // Explicit Invocation of Parameterized Constructor.
}
23. Situations when constructors are called.
2. When call by value is used to pass an argument to a
function.
length add(length a, length b)
{
length c;
c.feet = a.feet + b.feet;
c.inch = a.inch + b.inch;
if(c.inch > 12)
{ c.feet++; c.inch -= 12; }
return c;
}
main()
{
length x(5,6), y(3,8), z;
z = add(x,y);
}
Copy Constructor.
Create Copy of
x is a & y is b
Invoke Regular
Constructor
Invoke Default
Constructor
Invoke add() with 2
arguments x and y.
x y
Take copy of Actual
Arguments x and y.
b(y)a(x)
24. Situations when constructors are called.
3. When the function returns an instance of a class.
length add(length a, length b)
{
length c;
c.feet = a.feet + b.feet;
c.inch = a.inch + b.inch;
if(c.inch > 12)
{ c.feet++; c.inch -= 12; }
return c;
}
main()
{
length x(5,6), y(3,8), z;
z = add(x,y);
}
Copy Constructor.
Create Temporary
Instance of C.
Invoke Regular
Constructor Invoke Default
Constructor
c
Temporary instance
25. 4. Create an object using ‘new’ operator during runtime.
new operator is used with pointers and pointers are created by placing * before
pointer name.
int main()
{
length *a = new length;
length *b = new length(5,8);
length *c = new length(b);
}
Create 3 objects a,b
and c using new
Operator at run time.
length ()
{ feet = inch = 0; }
length (int a1, int a2)
{
feet=a1; inch = a2;
}
Copy Constructor
length (length &arg)
{
feet = arg.feet;
inch = arg.inch;
}
5 8
Reference of b.
Assign feet and
inch of ‘b’ in
newly created
Objecte.
26. Copy Constructor. Constructor that initialize an object with another object of
same class is called Copy Constructor. If you have not defined a Copy Constructor,
the compiler creates implicitly-defined copy constructor. The process of initializing
through a copy constructor is known as Copy Initialization. The general form of a
copy constructor is class_name ( class_name &obj ) { ….. }
class length
{
int feet, inch;
public:
length (int a1, int a2) { feet = a1; inch = a2; }
length ( length &arg )
{
feet = arg.feet;
inch = arg.inch;
}
};
main()
{
length a(8,5); // Passing 2 int to Regular Constructor.
length b(a);
}
Parameterized Constructor.
Here The constructor is invoked by giving 2
integers, representing Feet(8) and Inch(5).
Copy Constructor.
The constructor is invoked by
giving Reference of an Object,
and the data of newly created
object are initialized using
values of referencing Object.
Passing previously created object to Copy
Constructor.
a(Ref)
8,5
85
27. Copy Constructor. Constructor that initialize an object with another object of
same class is called Copy Constructor. If you have not defined a Copy Constructor,
the compiler creates implicitly-defined copy constructor. The process of initializing
through a copy constructor is known as Copy Initialization. The general form of a
copy constructor is class_name ( class_name &obj ) { ….. }
# include <iostream.h>
class length
{
int feet, inch;
public:
void output()
{ cout<<“Length is ” << feet <<“,”<< inch; }
};
main()
{
length a;
length b(8,5);
length c(b); // OR length c = b;
a.out(); b.out(); c.out();
}
length() { feet = inch = 0; }
length (int a1, int a2)
{ feet = a1; inch = a2; }
length ( length &arg )
{
feet = arg.feet; inch = arg.inch;
}
b(8,5)
58
b.feet(8)b.inch(5)
Constructor that
initialize an object
with another object is
called Copy
Constructor.
Invoke constructor
with 2 int.
Default Constructor.
OUTPUT
Length is 0,0
Length is 8,5
Length is 8,5
28. When is a Copy Constructor Called ?.
When an object is initialized
with another object.
(See )
When an object is passed
by Value.
(See )
When a Function Return
an object.
(See )
Why the argument to a Copy Constructor is passed by Reference ?. When an
Object is passed by value, a copy of the object is created through a Copy
Constructor. i.e Copy Constructor try to create another copy. That is, creating a copy
of the object for itself, thus it calls itself. In fact it calls itself again and again until the
compiler runs out of memory. So the Argument must be passed by value.
When a function being invoked by giving reference of an object, the memory address
of the object is passed to that function. i.e. any copy of that object will not be
created. The function works with previously created object.
The constructor is invoked by giving Reference of an Object, it will not create copy of
argument, But it will take address of previously created object. And the data of newly
created object are initialized using values of previously created Object.
29. A function being called by value, it will try to
create a copy of the argument object, by
invoking Copy Constructor.
Before entering to the Copy Constructor, try to
create a new copy of passing object by
invoking Copy Constructor.
Before entering to the Copy Constructor,
try to create a new copy of passing object
by invoking Copy Constructor.
Before entering to the Copy Constructor,
try to create a new copy of passing object
by invoking Copy Constructor.
Before entering to the Copy Constructor,
try to create a new copy of passing object
by invoking Copy Constructor.
30. Order of Constructor Invocation. Since every time an object is created the
constructor is automatically invoked. The Objects are constructed in the order they
are defined.
# include <iostream.h>
class test
{
int no;
public:
test(int arg)
{
no = arg;
cout << “nCreating an object Having the Value “ << no;
}
};
main()
{
test a(1), b(2), c(3), d(4), e(5);
}
OUTPUT
Creating an object Having the Value 1
Creating an object Having the Value 2
Creating an object Having the Value 3
Creating an object Having the Value 4
Creating an object Having the Value 5
4th d
no =4
3rd c
no =3
5th e
no =5
1st a
no =1
2nd b
no =2
Show
31. Order of Constructor Invocation.
A class Contains objects of
another class as its members, the
constructors for member objects
are invoked first, and then only
the constructor for containing
class is invoked.
# include <iostream.h>
class A
{
public:
A()
{ cout << "nnConstructing Object of Class A."; }
};
class B
{
public:
B()
{ cout << "nnConstructing Object of Class B."; }
};
class C
{
A a_obj;
B b_obj;
public:
C()
{ cout << "nnConstructing Object of Class C."; }
};
main()
{
clrscr();
C c_obj;
}
Show
OUTPUT
Constructing Object of Class A
Constructing Object of Class B
Constructing Object of Class C
32. # include <iostream.h>
class Subject
{
int days, subjectno;
public:
Subject(int d = 123, int sn = 101)
{
days = d; subjectno = sn;
cout << "nnConstructing Subject.";
}
};
class Student
{
int rollno;
float marks;
public:
Student()
{
cout << "nnConstructing Student.";
rollno = 0; marks = 0.0;
}
};
class Admission
{
Subject sub;
Student stud;
float fees;
public:
Admission()
{
cout << "nnConstructing Admission.";
fees = 0.0;
}
};
int main()
{
Admission adm;
cout << "nnBack in main().";
return 0;
}
OUTPUT
Constructing Subject.
Constructing Student.
Constructing Admission.
Back in main().
Show
Order of Constructor
Invocation. A class
Contains objects of another
class as its members, the
constructors for member
objects are invoked first,
and then only the
constructor for containing
class is invoked.
33. Dynamic Initialization of Objects. The Dynamic Initialization means that the
initial values may be provided during runtime.
# include <iostream.h>
class time
{
int h,m,s;
public:
time(int hh=0, int mm = 0, int ss=0)
{
h = hh; m = mm; s = ss;
}
void out()
{
cout << “nGiven Time is “ << h
<< “:” << m << “:” << s;
}
};
main()
{
int a,b,c;
cout<<“nEnter Hour, Minutes and Seconds.”;
cin >> a >> b >> c ;
time t(a, b, c);
t.out();
}
Input hour, minute and seconds
from keyboard, when the
program being execute.
a
OUTPUT
Enter Hour, Minutes and Seconds. 2 40 50
Given Time is 2 : 40 : 50
Inputted hour (a), minute
(b) and seconds (c) are
passed to the constructor.
b c
Show
34. Constant and Reference Variables/Members.
Constant Variables / Members. Constant refers to fixed values that the
program may not alter. Constants also called literals. To make a constant, place
the keyword ‘const’ before data declaration.
const int a = 10;
……………………..
……………………..
a = 25; // Error. A constant member may not alter.
Reference Variables / Members. Reference variables is an alias (another
name) for a pre-defined variable. That is a same value can be accessed by any
of the two names. A reference is an implicit pointer. To make an alias, place ‘&’
before the variable name. It must be initialized when it is declared.
int mian()
{
int a=10,b=20, sum, &tot=sum;
tot = a + b;
cout << “nnValue of tot = “ << tot;
cout << “nnValue of sumt = “ << sum;
}
‘tot’ becomes reference (alias) of ‘sum’ by
placing ‘&’ before ‘tot’
Same value can be
accessed by any of the two
names ‘tot’ and ‘sum’.
Both are 30.
35. Initialization of ‘const’ and Reference Members. I your calss contains a
constant / reference as member field, then traditional way of initialization will not
work, consider following code.
struct stud_name
{
char first_name[20];
char last_name[20];
} Snam = { “Anil”, “Krishna”};
class student
{
stud_name &name;
const int max_marks;
int roll no, marks_get;
public:
student()
{
name = Snam;
max_marks = 300;
roll_no = 100; marks_get = 216;
}
};
max_marks
becomes
Constant.
‘name’ becomes
reference (alias) of
‘Snam’ by placing ‘&’
before ‘name’
We can’t initialize
‘name’ and
‘max_marks’ in
this way. Because
they are ‘const’
and Reference
members.
Initialize
Snam.first_name = “Anil”
Snam.last_name = “Krishna”
36. A constructor can initialize ‘const’ and reference members of its class through a
mem-initialization list that appears in the function header.
struct stud_name
{
char first_name[20];
char last_name[20];
} Snam = { "Anil", " Krishna“ };
class student
{
int roll_no, marks_get;
const int max_marks;
stud_name &name;
public:
};
student() : name(Snam), max_marks(300)
{
roll_no = 100; marks_get = 216;
}
Mem-Initialization List.
Initialize
Snam.first_name = “Anil”
Snam.last_name = “Krishna”
Will initialize
‘const’ member
max_marks
with 300.
Will initialize reference
member name with
Snam.
MEM-INITIALIZATION LIST
student() : max_marks(300), name(Snam)
Will initialize other
data members.
37. # include <iostream.h>
struct stud_name
{
char first_name[20];
char last_name[20];
} Snam = { "Anil", " Krishna“ };
class student
{
int roll_no, marks_get;
const int max_marks;
stud_name &name;
public:
student() : max_marks(300), name(Snam)
{
roll_no = 100; marks_get = 216;
}
void out()
{
cout << "nName " << name.first_name << name.last_name;
cout << "nRoll No = " << roll_no;
cout << "Marks Get"<<marks_get<<"Max.Mark"<< max_marks;
}
};
void main()
{
student a;
a.out();
}300
Snam (Anil Krishna)
Show
‘name’ becomes
reference (alias) of
‘Snam’ by placing ‘&’
before ‘name’
max_marks become constant
member by placing the
keyword ‘const’.
38. # include <iostream.h>
# include <string.h>
class student
{
char name[20]; int roll, marks;
int &std;
const int max;
public:
void out()
{
cout << "nnName : " << name <<
" Roll No : " << roll <<
"nnStandared : " << std <<
" Marks " << marks << " Out of “
<< max;
}
student(char nam[], int rol, int mrk, int &st, int mx) : std(st), max(mx)
{
strcpy(name, nam);
roll = rol; marks = mrk;
}
};
void main()
{
char nam[20];
int rol, st, mrk, max;
cout << “Enter Name of Student & Roll No ";
cin >> nam >> rol;
cout << “Enter STD, Marks get, Max. Mark";
cin >> st >> mrk >> max;
student a ( nam , rol, mrk, st, max);
a.out();
getch();
}
Show
Raman 100
216 300
OUTPUT
Name : RAMAN Roll No : 100
Standard : 12 Marks 216 Out of 300
12
39. Constructor Overloading. Constructor Functions can also be Overloaded. All
constructors has same name, but they differs in function signature.
# include <iostream.h>
class deposit
{
long int prin_amt;
int time;
float rate, tot_amt;
public:
deposit();
deposit(long p, int t, float r);
deposit(long p, int t);
deposit(long p, float r);
void cal_amt();
void display();
};
void deposit :: cal_amt()
{ tot_amt= prin_amt + (prin_amt*time*rate); }
void deposit :: display()
{
cal_amt();
cout << "nnPrincipal Amount " << prin_amt
<< "nnPeriod " << time << " years"
<< "nnRate " << rate
<< "nnTotal Amount " << tot_amt;
}
main()
{
d1.display(); d2.display();
d3.display(); d4.display();
}
deposit :: deposit(long p, int t)
{ prin_amt=p; time = t; rate = 0.08; }
deposit :: deposit()
{ prin_amt = time = rate = 0; }
deposit :: deposit(long p, int t, float r)
{ prin_amt = p; time = t; rate = r; }
deposit :: deposit(long p, float r)
{ prin_amt = p; rate = r; time = 2; }
deposit d4(3000,0.12f); // Click Me
deposit d1; // Click Me
deposit d3(2000, 2,0.07f); // Click Me
deposit d2(4000, 1); // Click Me4000 1
2000 2 0.07
3000 0.12
0
40. # include <iostream.h>
class employee
{
int age_in_years;
public:
void out()
{
cout << "nnMy Age is " << age_in_years << " years.";
}
};
main()
{
employee e;
int ag;
e.age(35);
ag = e.age();
e.out();
cout << "nnAge Returned is " << ag;
getch();
}
The Overloading of member functions may be used to either set or retrieve values
from a class. When we invoke function without parameter, it will return value. Invoke
the function with any parameter, it will set the member data.
int age()
{
return age_in_years;
}
void age(int a)
{
age_in_years = a;
}
Invoke the function with
the value 35, it will set
age_in_years = 35.
Invoke the function without
any value, it will return
current value of age_in_years
(35).
Click Me
35
35
41. Default Arguments versus Overloading. Using default arguments gives the
appearance of overloading, because the function may be called with an optional number of
arguments.
float amount ( float principal, int time = 2, float rate = 0.08);
cout << amount(3000); Here function amount(3000) is invoked by passing only one
Argument. Missing parameters time and rate get default values 2 and 0.08 respectively.
cout<<amount(3000,4); Here function amount(3000,4) is invoked by passing 1st & 2nd
argument. Principal = 3000 and time = 2. Missing parameters rate get default values 0.08.
cout << amount(2500,5,0.12); Here function amount(2500,5,0.12) is invoked by
passing all argument. Principal = 3000 and time = 2 and rate = 0.12.
cout << amount(2000,0.13); Here function amount(2000,0.13) is invoked by
passing values principal = 2000 and rate = 0.13. But C++ will not interpret like this. C++
will take 0.13 to be the argument value of time. 0.13 converted to ‘int’ thus time = 0. And
rate get default value 0.08.
Only the arguments on the right side can be defaulted. If you want to default a middle
argument, then all the arguments on its right must be also defaulted.
42. # include <iostream.h>
void amount(float prin_amt, , )
{
float int_amt = prin_amt * rate * time;
cout << "nnPrincipal Amount : " << prin_amt
<< "Time : " << time << " years"
<< "Rate : " << rate
<< "Interest Amount : " << int_amt;
}
void main()
{
}
cout << "nnnCASE 1. amount(3000)";
amount(3000); //Click Me
Invoke function with
one parameter 3000,
missing arguments
‘time’ and ‘rate’ has
get default values 2
and 0.08.
Invoke Function with 2
arguments
amount(2500) and
time(3yrs). Missing
argument ‘rate’ will
get default value 0.08.
Invoke function
with all 3
arguments.
Amount(2300),
time(3yrs) and
rate(0.11).
cout << "nnnCASE 2. amount(3000,3)";
amount(2500,3); //Click Me
cout << "nnnCASE 3. amount(2500,5,0.12)";
amount(2300,3,0.11); //Click Me
cout << "nnnCASE 4. amount(2000,0.13)";
amount(2500,0.8); //Click Me
int time = 2 float rate=0.08
3000
2 0.08
2500 3
2300 3 0.11
2500 0.8
43. # include <iostream.h>
void calculate(float prin_amt, int time, float rate)
{
float int_amt = prin_amt*rate*time;
cout << "nPrincipal Amount : " << prin_amt
<< "Time : " << time << " years"
<< "Rate : " << rate
<< "Interest Amount : " << int_amt;
}
void main()
{
}
void amount(float prin_amt, float rate)
{
int time = 2;
calculate(prin_amt, rate, time);
}
void amount(float prin_amt, int time, float rate)
{
calculate(prin_amt, rate, time);
}
void amount(float prin_amt, int time)
{
float rate = 0.08;
calculate(prin_amt, rate, time);
}
void amount(int time, float rate)
{
float prin_amt = 2000;
calculate(prin_amt, rate, time);
}
void amount(float prin_amt)
{
int time = 2; float rate = 0.08;
calculate(prin_amt, rate, time);
}
cout << "nCase 5: amount(6,0.07)";
amount(6,0.07); //Click Me
cout << "nCase 1: amount(2000.0)";
amount(2000.0f); //Click Me
cout << "nCase 2: amount(2500.0,3)";
amount(2500.0f,3); //Click Me
cout <<“nCase 3: amount(2300.0,3,0.11)";
amount(2300.0f,3,0.11f); //Click Me
Cout << “nCase 4: amount(2000.0,0.12f)";
amount(2000.0f,0.12f); //Click Me
Case 1:
Invoke Function with
one float argumrnt.
Which is Pricipal
Amount(2000) and
appropriate function
will declare time = 2
and rate =0.08.
Finally jump to
calculate () with all 3
values.
Case 2:
Invoke Function with
2 argumrnt.
They are float Pricipal
Amount(2500) and int
time(3). Appropriate
function will declare
rate =0.08. Finally
jump to calculate ()
with all 3 values.
Case 3:
Invoke Function with
all 3 argumrnts.
They are float
Pricipal
Amount(2300), int
time(3yrs) and float
rate(0.11). Finally
jump to calculate ()
with all 3 values from
appropriate function..
Case 4
Invoke Function with 2 float
argumrnt.
They are Pricipal
Amount(2000) & rate(0.12).
The appropriate function will
declare time = 2. Finally
jump to calculate () with all
3 values.Case 5:
Invoke Function with 2
argumrnt.
They are int time(6yrs)
and float rtae(0.07)
and appropriate
function will declare
float principal
amount(2000). Finally
jump to calculate ()
with all 3 values.
44. The Advantages of Function Overloading over Default
Arguments.
Default arguments might not work for all possible combinations of
arguments whereas a function may be overloaded for all possible
combinations of arguments.
With Function Overloading, multiple function definitions can be executed but
with default arguments exactly one function definition is executed.
By declaring an overloaded function, you save the compiler from the trouble
of pushing the default argument value on the function call stack and you
save the function from the trouble of testing the default value.
With Using Overloading in place of default arguments is more beneficial.
45. Special Characteristics of Constructors.
1. Constructor Functions are invoked automatically when the objects are created.
2. If a class has a constructor, each object of that class will be initialized before any
use is made of the object.
3. Constructor function obey the usual access rules. That is, private, protected
constructors are available only for member and friend functions, however, public
constructors are available for all the functions. Only the functions that have access
to the constructor of a class can create an object of the class.
4. No return type can be specified for constructor.
5. They can’t not be inherited, through a derived class can call the base class
constructor.
6. A constructor may not be static.
7. Default constructors and copy constructors are generated by the compiler where
needed. Generated Constructors are public.
8. Like other functions, constructors can also have default arguments.
9. It is not possible to take the address of a constructor.
10. An object of a class with a constructor can not be a member of union.
11. A member function may be called from within a constructor.
12. A constructor can be used explicitly to create new objects of its class type, using the
syntax Class_name (expression-list) For example Sample obj1 = Sample (13, 22, 42);
46. Destructors. A destructor, as the name itself suggests, is used to destroy the
objects that have been created by the constructor. A destructor is also a member
function whose name is the same as the class name but is preceded by tilde (‘~’). A
destructor take no arguments and no return types can be specified. It is calleld
automatically by the compiler when an object is destroyed.
Need for Destructor.
During construction of an object, resources may be allocated for use. These
allocated resources must be deallocated before the object is destroyed. A destructor
performs all clean-up tasks like closing a file, releasing memory area.
class test
{
public:
test() { // Constructor; }
};
~test()
{
// Destructor;
}
A member
function
having the
name of its
class is called
Constructor. So
it is
Constructor.
A member function
having the name of
its class, but
preceded with ‘~’ is
called Destructor.
So it is Constructor.
47. # include <iostream.h>
class length
{
int feet, inch;
public:
};
length()
{
cout << “nNow Creating New Object”;
}
~length()
{
cout << “nnNow Destroying Object”;
}
void main()
{
length a;
………….
………….
………….
}
Destructor deallocate resources before the
object is destroyed. A destructor performs all
clean-up tasks like closing a file, releasing
memory area.
OUTPUT
Now Creating New Object
Now Destroying Object
A constructor allocate
all resources for the
new Object.
Both Constructors and Destructors
will invoke automatically, when
objects being create and destroy.
The object will be destroyed before
its scope/life goes out.
Click Me
Scope of object ‘a’
will be end here.
Destructor will be
called at this
point.
a
48. Some Characteristics of Destructors
1. Destructor functions are invoked automatically when the objects are destroyed.
2. You can have only one destructor for a class. In other words destructor can not
be overloaded.
3. If a class has a destructor, each object of that class will be deinitialized before the
objects goes out of scope. (Local objects at the end of the block defining them
and global and static objects at the end of the program.
4. Destructor functions also obey the usual access rules as other member functions
do.
5. No argument can be provided to a destructor, neither does it return any value.
6. The can not be inherited.
7. A destructor may not be static.
8. It is not posible to take the address of a destructor.
9. Member functions may be called from within a destructor.
10.An object of a class with destructor can not be a member of a union.