Constructorssss
Constructorssss
A constructor is a special member function of a class that is automatically invoked whenever an object
of that class is created. Its primary purpose is to initialize the data members of the object.
1. Same Name as the Class: A constructor must have the same name as the class it belongs to.
2. No Return Type: It doesn't have a return type, not even void.
3. Automatically Invoked: It's automatically called when an object of the class is created.
4. Initialization: It's used to initialize the member variables of the object.
5. Overloading: You can have multiple constructors with different parameter lists, allowing for
flexible object initialization.
Types of Constructors:
Default Constructor:
Parameterized Constructor:
Copy Constructor:
Programs:
#include<iostream.h>
class Box
{
public:
int length;
int breadth;
int height;
// Default constructor
Box() {
length = 0;
breadth = 0;
height = 0;
}
};
void main()
{
Box box1;
cout << "Box 1 Details:" << endl;
cout << "Length: " << box1.length << endl;
cout << "Breadth: " << box1.breadth << endl;
cout << "Height: " << box1.height << endl;
}
Parameterized Constructor
#include<iostream.h>
#include<conio.h>
class Box
{
public:
int length;
int breadth;
int height;
// Default constructor
Box()
{
length = 0;
breadth = 0;
height = 0;
}
// Parameterized constructor
Box(int l, int b, int h)
{
length = l;
breadth = b;
height = h;
}
};
void main()
{
clrscr();
Box box1;
cout << "Box 1 Details:" << endl;
cout << "Length: " << box1.length << endl;
cout << "Breadth: " << box1.breadth << endl;
cout << "Height: " << box1.height << endl;
class Box
{
public:
int length;
int breadth;
int height;
// Default constructor
Box()
{
length = 0;
breadth = 0;
height = 0;
}
// Parameterized constructor
Box(int l, int b, int h)
{
length = l;
breadth = b;
height = h;
}
// Copy constructor
Box(Box& obj)
{
length = obj.length;
breadth = obj.breadth;
height = obj.height;
}
};
void main()
{
clrscr();
Box box1;
cout << "Box 1 Details:" << endl;
cout << "Length: " << box1.length << endl;
cout << "Breadth: " << box1.breadth << endl;
cout << "Height: " << box1.height << endl;