0% found this document useful (0 votes)
11 views25 pages

Constructors

The document explains constructors and destructors in C++, highlighting their roles in initializing and deallocating memory for class objects. It details the characteristics of default and parameterized constructors, constructor overloading, and the use of destructors for cleaning up resources. Examples of class definitions and object creation illustrate these concepts in practice.
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)
11 views25 pages

Constructors

The document explains constructors and destructors in C++, highlighting their roles in initializing and deallocating memory for class objects. It details the characteristics of default and parameterized constructors, constructor overloading, and the use of destructors for cleaning up resources. Examples of class definitions and object creation illustrate these concepts in practice.
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/ 25

Constructors and

Destructors
What is a Constructor?

• It is tedious to initialize data members each time you create object of the class.
• It would be simple and more convenient to initialize data members at the time of
object creation first time.
• The automatic initialization is performed through the use of a constructor.
• Its name is same as the name of the class
• It has no return type
• It is similar to a member function of the class.
• Once define, it is automatically called immediately after the object is created, before
the DOT operator completes.
• When you do not explicitly define a constructor, C++ creates a default constructor
• Default constructor is sufficient for simple classes.
Constructors

• Constructor is used to initialize an object of the class and assign


values to data members corresponding to the class. While destructor
is used to deallocate the memory of an object of a class.
• Can be used to access private member functions.

To create a constructor, use the same name as the class,


followed by parentheses ()
class MyClass { // The class Note: The constructor has the
public: // Access specifier same name as the class, it is
MyClass() { // Constructor always public, and it does
cout << "Hello World!"; not have any return value.
}
};

int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
The Default Constructor
• A default constructor is a constructor that takes no arguments. Like
regular functions, constructors may accept arguments, have default
arguments, be declared inline, and be overloaded.
• If you write a class with no constructor whatsoever, when the class is
compiled C++ will automatically write a default constructor that does
nothing.
// C++ program to demonstrate the use of default constructor

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;

public:
// default constructor to initialize variable
Wall() {
length = 5.5;
cout << "Creating a wall." << endl;
cout << "Length = " << length << endl;
}
};

int main() {
Wall wall1;
return 0;
}
Constructor Parameters

• Constructors can also take parameters (just like regular functions),


which can be useful for setting initial values for attributes.
• A constructor can accept arguments when an object is created.
• The following class have brand, model and year attributes, and a
constructor with different parameters.
• Inside the constructor we set the attributes equal to the constructor
parameters (brand=x, etc). When we call the constructor (by creating
an object of the class), we pass parameters to the constructor, which
will set the value of the corresponding attributes to the same:
• class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};

int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
// C++ program to calculate the area of a wall
#include <iostream>
int main() {
using namespace std; // create object and initialize data members
// declare a class Wall wall1(10.5, 8.6);
class Wall { Wall wall2(8.5, 6.3);
private:
cout << "Area of Wall 1: " << wall1.calculateArea() <<
double length; endl;
double height; cout << "Area of Wall 2: " << wall2.calculateArea();
public:
return 0;
// parameterized constructor to initialize
variables }
Wall(double len, double hgt) {
length = len;
height = hgt;
}
double calculateArea() {
return length * height;
}
};
Defining constructor outside of class
Just like functions, constructors can also be defined outside the class.
First, declare the constructor inside the class, and then define it outside
of the class by specifying the name of the class, followed by the scope
resolution :: operator, followed by the name of the constructor (which
is the same as the class):
• class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};

// Constructor definition outside the class


Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}

int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
# include <iostream.h> # include <conio.h>
# include <math.h> class power
{
private:
int num; int power; int ans;
public :
power (int n=9,int p=3); //declaration of constructor with default argu-ments
void show( )
{
cout <<"\n"<<num <<" raise to "<<power <<" is " <<ans;
}
};
power :: power (int n,int p )
{
num=n; power=p; ans=pow(n,p);
}
Int main( )
{
power p1,p2(5);
p1.show( );
p2.show( );
return 0;
}
Constructor
Overloading
Overloading Constructors
• A class can have more than one constructor

• Overloaded constructors in a class must have different parameter


lists:
Rectangle();
Rectangle(double);
Rectangle(double, double);
Continues...
#include <iostream>
using namespace std;

class construct
{
int main()
public: {
float area;
// Constructor Overloading
// Constructor with no parameters // with two different constructors
construct() // of class name
{ construct o;
area = 0;
} construct o2( 10, 20);

// Constructor with two o.disp();


parameters
o2.disp();
construct(int a, int b)
{ return 1;
area = a * b; }
}

void disp()
{
cout<< area<< endl;
}
};
Dynamic Constructor
• This constructor is used to allocate the memory to the objects at the
run time. The memory allocation to objects is allocated with the help
of 'new' operator. By using this constructor, we can dynamically
initialize the objects.
#include <iostream.h>
void main()
#include <conio.h>
class Account {
{ clrscr();
private:
int an,bal;
int account_no;
int balance; cout<< "Enter account no : ";
public : cin >> an;
Account(int a,int b) cout<< "\nEnter balance : ";
{
cin >> bal;
account_no=a;
balance=b; Account *acc=new Account(an,bal); //dynamic
} constructor
void display()
acc->display(); //'->' operator is used to access the
{
cout<< "\nAccount number is : "<< account_no;
method
cout<< "\nBalance is : " << balance; getch();
} }
};
Destructors

• A destructor is a member function that is automatically called when


an object is destroyed.

• For example, a common use of destructors is to free memory that was


dynamically allocated by the class object
• Classes may also only have one destructor. Because destructors take
no arguments, the compiler has no way to distinguish different
destructors.
#include <iostream>
using namespace std;
class demo
{
public:
demo();
~demo();
};
demo::demo(){
cout<<"welcome to constructor \n";}
demo::~demo(){
cout<<"this is destructor \n";}
int main()
{
demo obj;
cout<<"the program demonstrate an object\n";
cout<<"with a constructor and destructor\n";
return 0;
#include<iostream>
using namespace std;
class Demo {
private:
int num1, num2;
public:
Demo(int n1, int n2) {
cout<<"Inside Constructor"<<endl;
num1 = n1;
num2 = n2;
}
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
~Demo() {
cout<<"Inside Destructor";
}
};
int main() {
Demo obj1(10, 20);
obj1.display();
return 0;

You might also like