
Constructor
Constructor is a special kind of member method which never return a value. It is used to initialize an object.
- Constructor name is the class name.
- It is self-executed when an object is created or initialize.
- Constructor should be public.
How to use constructor?
#include <iostream> using namespace std; class Student { public: string studentName; int sAge; // constructor Student(string name, int age) { studentName = name; sAge = age; } void printInfo() { cout << "Student name is : " << studentName << endl; cout << "Student age is : " << sAge << endl; } }; int main(int argc, char const *argv[]) { Student s1("Online Vidyalay", 32); // calling method s1.printInfo(); return 0; } // output // Student name is : Online Vidyalay // Student age is : 32
Types of constructor
There are main three types of constructor in c++ programming
- Default constructor
- Parameterized constructor
- Copy constructor
1. Default constructor
A constructor which takes zero number of arguments is called a default constructor (we don’t need to pass any argument at the time of object creation).
- If we did not create a default constructor, then the c++ compiler automatically creates a default constructor.
Example
#include <iostream> using namespace std; class Student { public: string studentName; int sAge; // default constructor Student() { studentName = ""; sAge = 0; } void printInfo() { cout << "Student name is : " << studentName << endl; cout << "Student age is : " << sAge << endl; } }; int main(int argc, char const *argv[]) { Student s1; s1.studentName = "Online Vidyalay"; s1.sAge = 32; // calling method s1.printInfo(); return 0; } // output // Student name is : Online Vidyalay // Student age is : 32
2. Parameterized constructor
A constructor which takes at least one argument is called a parameterized constructor.
#include <iostream> using namespace std; class Student { public: string studentName; int sAge; // constructor Student(string name, int age) { studentName = name; sAge = age; } void printInfo() { cout << "Student name is : " << studentName << endl; cout << "Student age is : " << sAge << endl; } }; int main(int argc, char const *argv[]) { Student s1("Online Vidyalay", 32); // calling method s1.printInfo(); return 0; } // output // Student name is : Online Vidyalay // Student age is : 32
2. Copy constructor
It passes reference of an object as a parameter called copy constructor.
There are two ways to execute a copy constructor itself.
- shallow copy
- deep copy