Constructors
Constructors
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
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
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
};
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
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);
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