Examples of Constructors in C++
The below examples demonstrate how to declare constructors for a class in C++:
Example 1: Defining the Constructor Within the Class
C++
// defining the constructor within the class #include <iostream> using namespace std; class student { int rno; char name[50]; double fee; public : // constructor student() { cout << "Enter the RollNo:" ; cin >> rno; cout << "Enter the Name:" ; cin >> name; cout << "Enter the Fee:" ; cin >> fee; } void display() { cout << endl << rno << "\t" << name << "\t" << fee; } }; int main() { student s; // constructor gets called automatically when // we create the object of the class s.display(); return 0; } |
Output
Enter the RollNo:121
Enter the Name:Geeks
Enter the Fee:5000
121 Geeks 5000
Example 2: Defining the Constructor Outside the Class
C++
// defining the constructor outside the class #include <iostream> using namespace std; class student { int rno; char name[50]; double fee; public : // constructor declaration only student(); void display(); }; // outside definition of constructor student::student() { cout << "Enter the RollNo:" ; cin >> rno; cout << "Enter the Name:" ; cin >> name; cout << "Enter the Fee:" ; cin >> fee; } void student::display() { cout << endl << rno << "\t" << name << "\t" << fee; } // driver code int main() { student s; s.display(); return 0; } |
Output
Enter the RollNo:11
Enter the Name:Aman
Enter the Fee:10111
11 Aman 10111
Note: We can make the constructor defined outside the class as inline to make it equivalent to the in class definition. But note that inline is not an instruction to the compiler, it is only the request which compiler may or may not implement depending on the circumtances.
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor.
- Constructor is a member function of a class, whose name is the same as the class name.
- Constructor is a special type of member function that is used to initialize the data members for an object of a class automatically when an object of the same class is created.
- Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as a constructor.
- Constructors do not return value, hence they do not have a return type.
- A constructor gets called automatically when we create the object of the class.
- Constructors can be overloaded.
- A constructor can not be declared virtual.