L4 L5Constructors and Destructors 02-08-2017
L4 L5Constructors and Destructors 02-08-2017
L4 L5Constructors and Destructors 02-08-2017
DESTRUCTORS
(LECTURE 4-5)
Constructors
#include <iostream>
using namespace std;
class Counter
{
private:
unsigned int count;
public:
Counter() : count(0) //constructor
{ /*empty body*/
}
void inc_count() //increment count int main()
{ {
count++; Counter c1, c2; //define and initialize
} cout << “\nc1=” << c1.get_count();
int get_count() //return count //display
{ cout << “\nc2=” << c2.get_count();
return count; c1.inc_count(); //increment c1
} c2.inc_count(); //increment c2
}; c2.inc_count(); //increment c2
cout << “\nc1=” << c1.get_count();
//display again
cout << “\nc2=” << c2.get_count();
Initializer List
• In the Counter class the constructor must initialize the count member to 0.
You might think that this would be done in the constructor’s function body,
like this:
Counter()
{ count = 0; }
• This is not the preferred approach (although it does work).
initialize a data member:
Counter() : count(0)
{}
• If multiple members must be initialized, they’re separated by commas. The
result is the initializer list (sometimes called by other names, such as the
member-initialization list).
someClass() : m1(7), m2(33), m2(4)
{}
Default Constructor
• Constructor with no argument is called 'default
Constructor'.
• If compilers declares the 'default constructor', then it is said
to be 'implicitly declared default constructor„, otherwise
it is said to be a “explicitly declared default constructor”
or “user define no argument constructor”
Parameterized Constructor
• Constructors that can take arguments are called
parameterized constructors.
• Using this Constructor you can provide different values to data
members of different objects, by passing the appropriate
values as argument.
• The constructor sample can be modified to take arguments as
shown
class sample
{
int m,n;
public:
sample(int x, inty)
{m=x;
n=y;
}
};
Parameter passing for parameterized
constructor
We pass the initial values as arguments to the constructor
function when an object is declared.
Eg:
Sample s1(20,30); //implicit call
or
Sample s2=sample(20,30); //explicit call
Default Copy Constructor
• A copy constructor is used to declare and initialize an object
from another object.
• It‟s a one argument constructor whose argument is an object
of the same class as the constructor
• Eg:
sample s3(s2);
• Defines the object s3 and at the same time initializes it to the values of
object s2
• Another form of the statement is
sample s3=s2;
Default Copy Constructor
#include <iostream>
using namespace std;
Distance dist2(dist1); This causes the default copy constructor for the Distance class to
perform a member-by-member copy of dist1 into dist2. Surprisingly,
A different format has exactly the same effect, causing dist1 to be copied member-by-
member into dist3:
Distance dist3 = dist1;
Although this looks like an assignment statement, it is not.
Both formats invoke the default copy constructor, and can be used interchangeably.
Multiple constructor in a class
(Constructor overloading)
class sample
{
int m,n;
public:
sample(){m=0;n=0;};
sample(int x,int y){m=x;n=y;}
sample(sample &i){m=i.m;n=i.n;} // also called copy
constructor
};
class add
{ private: int num1, num2,sum;
public: add(int=0,int=0); //Default argument constructor to reduce
}; //the number of constructors
add::add(int n1, int n2)
{ num1=n1;
num2=n2;
sum=num1+num2;
O/p
cout<<“num1+num2=”<<sum<<endl;
num1+num2 =0
}
num1+num2 =5
int main()
num1+num2 =30
{
add obj1, obj2(5), obj3(10,20);
return 0;
}
Constructor with Default Arguments(cont…)
class add
{
private: int num1, num2,sum;
public: add(int=0,int=0); //Default argument constructor
add(){} //Default constructor
};
add::add(int n1, int n2)
{
num1=n1;
num2=n2; O/p
sum=num1+num2; Syntax Error:Call of
cout<<“num1+num2=”<<sum<<endl; Overloaded „add()‟ is
} ambiguous
int main()
{
add obj1, obj2(5), obj3(10,20);
return 0;
}
Important Points About Constructor
Q1:What happens when we write only a copy constructor – does
compiler create default constructor?
Compiler doesn‟t create a default constructor if we write any
constructor.
If user have not provided any of the following constructor, then
the compiler declares the default constructor for you:
a) Copy Constructor (User defined copy constructor)
b) Non-default constructor(Parameterized constructor)
c) default constructor (user define no argument constructor)
Joseph
john
jack
joseph john
joseph john jack
THIS POINTER
• The „this‟ pointer is passed as a hidden argument to all
nonstatic member function calls and is available as a local
variable within the body of all nonstatic functions.
• „this‟ pointer is a constant pointer that holds the memory
address of the current object.
• For example when you call obj.func(),
• „this‟ will be set to the address of obj.
• For a class X, the type of this pointer is „X* const‟.
• Also, if a member function of X is declared as const, then
the type of this pointer is „const X *const‟
Following are the situations where „this‟
pointer is used:
#include<iostream>
using namespace std;
class Test{
int x;
public:
void setX (int x){/* local variable is same as a member's name */
this->x = x; //This pointer is used
}
void print() { cout << "x = " << x << endl;
}
};
main function
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
To return reference to the calling object
• /* Reference to the calling object can be returned */
Test& Test::func ()
{
// Some processing
return *this;
}
36
• #include <iostream>
• using namespace std; int main(void) {
• class Box { Box Box1(3.3, 1.2, 1.5); // Declare box1
• public: Box Box2(8.5, 6.0, 2.0); // Declare box2
• // Constructor definition
• Box(double l = 2.0, double b = 2.0, if(Box1.compare(Box2)) {
double h = 2.0) { cout << "Box2 is smaller than Box1"
• cout <<"Constructor called." << <<endl;
endl; } else {
• length = l; cout << "Box2 is equal to or larger than
• breadth = b; Box1" <<endl;
• height = h; }
• }
• double Volume() { return 0;
• return length * breadth * height; }
• }
• int compare(Box box) {
• return this->Volume() >
box.Volume();
• }
• private:
• double length; // Length of a box
• double breadth; // Breadth of a box
• double height; // Height of a box
Practice Programs
• Create class account with data members name, accno,
balance, branch. Create 1 object with 4 inputs for account
class & display the same.
• WAP to add two complex numbers using constructors with
default argument.
38
Const qualifier
The qualifier const can be applied to the declaration of any
variable to indicate that its value will not be changed.
Example:
const int x = 5; // This will define x as constant with value 5
39
Const qualifier
void Foo( int * ptr, int const * ptrToConst, int * const constPtr, int const * const
constPtrToConst )
• {
*ptr = 0; // OK: modifies the "pointee" data
ptr = NULL; // OK: modifies the pointer