0% found this document useful (0 votes)
27 views20 pages

CH 4

Uploaded by

sparthsalunke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views20 pages

CH 4

Uploaded by

sparthsalunke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Chapter-4

Constructors and Destructors


 Constructors
• A constructor is a ‘special’ member function whose task is to initialize the objects of its class.
• It is special because its name is the same as the class name.
• It is called constructor because it constructs the values of data members of the class.
e.g.
class integer
{
int m , n;
public:
integer(void); // constructor declared
…………….
…………….
};
integer :: integer(void) // constructor defined
{
m=0;
n=0;
}
• When a class contains a constructor, it is guaranteed that an object created by the class will be initialized
automatically.
e.g. integer int1; // object int1 created
Not only creates the object int1 of type integer but also initializes its data members m and n to zero.
• A constructor that accepts no parameters is called the default constructor.
• The constructor functions have some special characteristics. These are:
1. They should be declared in the public section.
2. They are invoked automatically when the objects are created.
3. They do not have return types, not even void and therefore, and they cannot return values.
4. They cannot be inherited, though a derived class can call the base class constructor.
5. Like other C++ functions, they can have default arguments.
6. Constructors cannot be virtual.
7. We cannot refer to their addresses.

 Parameterized Constructors
• C++ permits us to achieve this objective by passing arguments to the constructor function when the objects are
created.
• The constructors that can take arguments are called parameterized constructors.
e.g.
class integer
{
int m, n;
public:
integer(int x, int y); // parameterized constructor
…………..
…………..
};
integer :: integer(int x, int y)
{
m=x;
n=y;
}
• when a constructor has been parametrized, the object declaration statement such as –
integer int1;
may not work.
• We must pass the initial values as arguments to the constructor function when an object is declared.
• This can be done in two ways:
1. By calling the constructor explicitly
2. By calling the constructor implicitly

3. integer int1= integer(0,100); //explicit call


This statement creates an integer object int1 and passes the values 0 and 100 to it.
2. integer int1(0,100); //implicit call
this method sometimes called as the shorthand method.
• The constructor functions can also be defined as inline functions.
e.g.
class integer
{
int m, n;
public:
integer(int x, int y) // inline constructor
{
m=x;
n=y;
}
………….
………....
};
Program
#include<iostream>
using namespace std;
class point
{
int x,y;
public:
point(int a, int b) // inline parameterized constructor definiton
{
x=a;
y=b;
}
void display()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
}; Output:
int main() Point p1=(1,1)
{ Point p2=(5,10)
point p1(1,1); //invoke parameterized constructor
point p2(5,10);
cout<<"Point p1=";
p1.display();
cout<<"Point p2=";
p2.display();
return 0;
}
 Multiple constructors in a class
• There are two kinds of constructors-
1. integer(); // No arguments
In this case, the constructor itself send data values and no values are passed by the calling program.
2. integer( int, int); // two arguments
In this case, the function call passes the appropriate values from main().
• C++ permits to use both these constructors in the same class.
e.g.
class integer
{
int m, n;
public:
integer()
{
m=0; //constructor 1
n=0;
}
integer(int a, int b)
{
m=a;
n=b; //constructor 2
}
integer(integer &i)
{
m=i.m; // constructor 3
n=i.n;
}
};

The declaration
integer I1;
Would automatically invoke the first constructor and set both m and n of I1 to zero.

integer I2(20,40);
Would call the second constructor which will initialize the data members m and n of I2 to 20 and 40 resp.

integer I3(I2);
would invoke the third constructor which copies the values of I2 into I3. Such constructor are called as copy constructor.

Note: when more than one constructor function is defined in a class, it is called as constructor is overloaded.

Cont..
Program:

#include <iostream>
using namespace std;
class ABC
{
private:
int x,y;
public:
ABC () //constructor 1 with no arguments
{
x = y = 0;
}
ABC(int a) //constructor 2 with one argument
{
x = y = a;
}
ABC(int a, int b) //constructor 3 with two argument
{
x = a;
y = b;
}
void display()
{
cout << "x = " << x << " and " << "y = " << y << endl;
Contd..
}
};
int main()
{
ABC cc1; //constructor 1
ABC cc2(10); //constructor 2
ABC cc3(10,20); //constructor 3
cc1.display();
cc2.display();
cc3.display();
return 0;
}

Output:
x = 0 and y = 0
x = 10 and y = 10
x = 10 and y = 20
// C++ program to illustrate the use of copy constructor
#include <iostream>
#include <string.h>
using namespace std;
// Class definition for 'student'
class student
{ int rno;
string name;
double fee;
public:
// Parameterized constructor
student(int, string, double);
// Copy constructor
student(student& t)
{
rno = t.rno;
name = t.name;
fee = t.fee;
cout << "Copy Constructor Called" << endl;
}
// Implementation of the parameterized constructor
// Function to display student details
void display();
};

Student :: student(int no, string n, double f)

rno = no;

name = n;

fee = f;

// Implementation of the display function


void student::display()

cout << rno << "\t" << name << "\t" << fee << endl;

}
int main()

// Create student object with parameterized constructor

student s(1001, "Manjeet", 10000);

s.display();
// Create another student object using the copy // constructor

student s1(s);

s1.display();

return 0;
}
 Constructor with default arguments
• e.g.
complex( float real, float imag=0);
The default value for the imag is zero. Then the statement
complex c(5.0);
assigns the value 5.0 to the real variable and 0.0 to imag.
• However, the statement
complex c(2.0,3.0);
assign 2.0 to real and 3.0 to imag.

 Dynamic initialization of objects


• Class objects can be initialized dynamically too. i.e. the initial value of an object may be provided during run
time.
• Advantage of dynamic initialization is that we can provide various initialization formats, using overloaded
constructors.

Cont…
Program:

#include<iostream>
using namespace std;
class sample
{
int n;
float avg;
public:
sample(int p,float q)
{
n=p;
avg=q;
}
void disp()
{
cout<<"\n Roll number:- " <<n;
cout<<"\nAverage :- "<<avg;
}
};

Cont…
int main()
{
int a ;
float b;
cout<<"\nEnter the Roll Number=>";
cin>>a;
cout<<"\nEnter the Average=>";
cin>>b;

sample s(a,b); // dynamic initialization


s.disp();
return 0;
}

Output:

Enter the Roll Number=>35

Enter the Average=>567

Roll numbe:- 35
Average :- 567
 Dynamic Constructors
• The constructor can be used to allocate memory while creating objects.
• This will enable the system to allocate the right amount of memory for each object when the objects are not of the same
size, thus resulting in the saving of memory.
• Allocate of memory to objects at the time of their construction is known as dynamic constructors of objects. The
memory is allocated with the help of new operator.

 Destructors
• A destructor is used to destroy the objects that have been created by a constructor.
• Like, a constructor, the destructor is member function whose name is the same as the class name but is preceded by a
tilde.
e.g.
~ integer( )
{

}
• A destructor never takes any arguments nor does it return any value.
• It will be invoked implicitly by the complier upon exit from the program to clean up storage that is no longer accessible.
• It is good practice to declare destructors in a program since it releases memory space for future use.
Program
#include<iostream>
using namespace std;

int count=0;
class test1
{
public:
test1()
{
count++;
cout<<"\n\n Constrctor msg: Object number"<<count<<" created";
}
~test1()
{
cout<<"\n\n Disconstrctor msg: Object number"<<count<<" destroyed";
count--;
}
};

int main()
{
cout<<"Inside the main block...";
cout<<"\n\n Creating first object T1...";
Contd…
test1 T1;
cout<<"\n\n Inside block 1....";
cout<<"\n\n Creating two more objects T2 and T3...";

test1 T2,T3;

cout<<"\n\n Leaving Block1...";


cout<<"\n\n Back inside the main block...";
return 0;
}

Output:
Inside the main block...

Creating first object T1...

Constrctor msg: Object number1 created

Inside block 1....

Creating two more objects T2 and T3...

Constrctor msg: Object number2 created

Constrctor msg: Object number3 created

Leaving Block1...

Back inside the main block...

Disconstrctor msg: Object number3 destroyed

Disconstrctor msg: Object number2 destroyed

Disconstrctor msg: Object number1 destroyed

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy