In this guide we will learn about constructor, their types and how to use them in C++.
A constructor is a special member function with the same name as that of a class, which is used to initialize the object of the class. When we create an object, the constructor is automatically called.
Example:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
A constructor with no parameter/arguments passed is called a default constructor. It is called automatically even if the constructor is not defined.
Syntax:
class xyz { xyz() { } };
Example:
#include
using namespace std;
class Rectangle
{
public:
int length,breadth;
Rectangle()
{
length=100;
breadth=50;
}
};
int main()
{
Rectangle l;
Rectangle b;
cout<<"\nLength of rectangle is "<<l.length;
cout<<"\nBreadth of rectangle is "<<l.breadth;
}
Output:
A constructor where an argument/parameter is passed at the time of object creation is called a parameterized constructor.
Syntax:
class Marks { Marks(int m,int n) //Parameterized Constructor { //Statements } };
Example:
#include
using namespace std;
class Student{
public:
int marks,rollno;
Student(int r,int m)
{
rollno=r;
marks=m;
}
int roll()
{
return rollno;
}
int mark()
{
return marks;
}
};
int main()
{
Student s1(1,98);
Student s2(2,80);
cout<<"\nStudent 1 roll no. is "<<s1.rollno;cout<<" and marks is "<<s1.marks;
cout<<"\nStudent 2 roll no. is "<<s2.rollno;cout<<" and marks is "<<s2.marks;
}
Output:
It is a special type of constructor which is used to copy data members from one object into another object.
Syntax:
class Class_name{ Constructor_name(class_name &obj_name) { } };
Example:
#include using namespace std; class Item { public: int ino; string iname; public: Item(int p,string q) { ino=p; iname=q; } int getino() { cout<<ino; } int getiname() { cout<<", "<<iname; } }; int main() { Item S1(4,"Item 1"); Item S2=S1; cout<<"\nList in Object 1: "; S1.getino(); S1.getiname(); cout<<"\n\nList in Object 2: "; S2.getino(); S2.getiname(); }
Output:
Submitted by Akansh Upadhyay (akansh)
Download packets of source code on Coders Packet
Comments