C++ Constructors
We often want to initialize some or all the member variables for an object when you declare the object. C++ includes special provisions for such initializations. When we define a class, we can define a special kind of member function known as Constructors.
A Constructor is a member function that is automatically called when an object about to create. A Constructor is used to initialize the values of member variables and to do any other sort of initialization that may be needed. We can define a constructor the same way that we define any other member function, except for two points.
Characteristics of constructor
- It has the same name as that of the class to which it belongs.
- It is executed automatically whenever the class is instantiated.
- It does not have any return type.
- It is normally used to initialize the data members of a class.
- It is also used to allocate resources such as memory, to the dynamic data members of a class
Constructor Syntax
class classname { private: private members; public: classname(); //constructor declaration }; classname : : classname() { //constructor body definition }
Example
/* C++ program to demonstrate the working wit constructor*/ #include <iostream> #include <string.h> using namespace std; class student { private: int rno; char name[30]; unsigned marks; public: student(); //constructor prototype void display(); }; student::student() //constructor definition { rno = 111; //default rno strcpy(name, "Balu"); //default name marks = 550; //default marks } void student::display() { cout<<"Roll No = "<<rno<<endl; cout<<"Name = "<<name<<endl; cout<<"Marks = "<<marks<<endl; } int main() { student s1; s1.display(); return 0; }
[quote]
Output
[/quote]
Parameterized Constructors
Constructors can be invoked with arguments, just as in the case of functions. The arguments list can be specified within braces similar to the argument list in the function. Constructors with arguments are called parameterized constructors.
The distinguishing characteristic is that the name of the constructor functions has to be the same as that of its class name.
Parameterized constructors syntax
class classname { private: private members; public: classname(argument1, argument2); //constructor declaration }; classname : : classname(argument1, argument2) { //constructor body definition }
Example
/* C++ program to demonstrate the working wit parameterized constructors*/ #include <iostream> #include <string.h> using namespace std; class student { private: int rno; char name[30]; unsigned marks; public: student(int tempNo, char*tempName, unsigned tempMark) ; //constructor prototype void display(); }; student::student(int tempNo, char*tempName, unsigned tempMark) //constructor definition { rno = tempNo; strcpy(name, tempName); marks = tempMark; } void student::display() { cout<<"Roll No = "<<rno<<endl; cout<<"Name = "<<name<<endl; cout<<"Marks = "<<marks<<endl; } int main() { student s1(111,"Balu",545); s1.display(); return 0; }
Multiple Constructors in a class
In the first case, the constructor itself supplies the data values and no values are passed by the calling program. In the second case, the function call passes the appropriate values from main().
C++ permits us to use both these constructors in the same class. For example, we could define a class as follows :
/* C++ program to demonstrate the working wit parameterized constructors*/ #include <iostream> #include <string.h> using namespace std; class student { private: int rno; char name[30]; unsigned marks; public: student(); student(int tempNo); student(int tempNo, char* tempName); void display(); }; student::student() //constructor definition { rno = 111; strcpy(name, "Balu"); marks = 550; } student::student(int tempNo) //One Argument Constructors { rno = tempNo; strcpy(name, "Balu Naik"); marks = 450; } student::student(int tempNo, char* tempName) // Two Arguments Constructors { rno = tempNo; strcpy(name, tempName); marks = 600; } void student::display() { cout<<"Roll No = "<<rno<<endl; cout<<"Name = "<<name<<endl; cout<<"Marks = "<<marks<<endl; } int main() { student s1; s1.display(); student s2(222); s2.display(); student s3(333,"balututorial.com"); s3.display(); return 0; }
[quote]
Output:
[/quote]
This declares three constructors for the student class. The first constructor receives no arguments, the second receives one Integer arguments and the third receives two arguments of type an integer and char* as an argument. For example, the declaration student s1;
Would automatically invoke the first constructor and set all three members to default data. The statement student s2(222);
Would call the second constructor which will initialize the data members respectively. Finally, the statement student s3(333,"balututorial.com");
Would invoke the third constructor which copies the values of tempNo and tempName.In this class we can mention more than one constructor function is defined in a class, we say that the constructor is overloaded.
Overloaded constructors
/* C++ program to demonstrate the working with overloaded constructors*/ #include <iostream> #include <string.h> using namespace std; class student { private: int rno; char name[30]; unsigned marks; public: student(int tempNo); student(char* tempName); void display(); }; student::student(int tempNo) { rno = tempNo; strcpy(name, "Balu Naik"); marks = 450; } student::student(char* tempName) { rno = 333; strcpy(name, tempName); marks = 600; } void student::display() { cout<<"Roll No = "<<rno; cout<<" Name = "<<name; cout<<" Marks = "<<marks<<endl; } int main() { student s1(222); s1.display(); student s2("balututoril.com"); s2.display(); return 0; }
[quote]
Output:
[/quote]
Copy Constructor
A copy constructor is used to declare and initialize an object from another object. The parameters of a constructor can be of any of the data types except an object of its own class as a value parameter. However, a class’s object can be passed as a reference parameter. Thus the class specification is shown as:
class className { private: ………… public: className() className(className &obj); // copy constructor className(argument1,argument2); };
Such a constructor having a reference to an instance of its own class as an argument is known as copy constructor. There are 3 important places where a copy constructor is called.
- When an object is created from another object of the same type
- When an object is passed by value as a parameter to a function
- When an object is returned from a function
If a copy constructor is not defined in a class, the compiler itself defines one. This will ensure a shallow copy. If the class does not have pointer variables with dynamically allocated memory, then one need not worry about defining a copy constructor. It can be left to the compiler’s discretion.
But if the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor
Example
/* C++ program to demonstrate copy constructors*/ #include <iostream> using namespace std; class MyClass { int id; public : MyClass() { } MyClass (int x) { id=x; }; MyClass (MyClass& obj) { id=obj.id; } void display() { cout<<id<<endl; } }; int main() { MyClass A(100); // Object A is initialized MyClass B(A); //copy constructor called MyClass C=A; //copy constructor call again MyClass D; //Object D is created, but not initialized. D=C; // copy constructor not called A.display(); B.display(); C.display(); D.display(); return 0; }
[quote]
Output:100
[/quote]
Constructor with default arguments
Like any other function in C++, constructors can also be defined with default arguments. It any arguments are passed the creation of an object, the compiler selects the suitable constructor with default arguments.
Example
/* C++ program to demonstrate Constructor with default arguments*/ #include <iostream> using namespace std; class MyClass { private: int a, b, c; public: MyClass(int a = 1, int b = 2, int c = 3) { MyClass::a = a; MyClass::b = b; MyClass::c = c; }; void showNumbers(void) { cout << a << ' ' << b << ' '<< c << '\n'; }; }; int main(void) { MyClass one(1, 1, 1); MyClass defaults; MyClass happy(101, 101, 101); one.showNumbers(); defaults.showNumbers(); happy.showNumbers(); return 0; }
[quote]
Output:
[/quote]