How to Define the Constructor Outside the Class in C++?
A constructor is a special type of member function whose task is to initialize the objects of its class. It has no return type so can’t use the return keyword and it is implicitly invoked when the object is created.
- Constructor is also used to solve the problem of initialization.
- It is called after the object is created.
- Same name as of class.
Constructor Defined Outside the Class
The constructor can be defined outside the class but it has to be declared inside the class. Here, you will use the scope resolution operator.
The syntax for constructor definition outside class:
class class_name {
public:
class_name();
};// Constructor definition outside Class
class_name::class_name()
{
}
Example:
C++
// C++ program to define // constructor outside the // class #include <iostream> using namespace std; class GeeksForGeeks { public : int x, y; // Constructor declaration GeeksForGeeks( int , int ); // Function to print values void show_x_y() { cout << x << " " << y << endl; } }; // Constructor definition GeeksForGeeks::GeeksForGeeks( int a, int b) { x = a; y = b; cout << "Constructor called" << endl; } // Driver code int main() { GeeksForGeeks obj(2, 3); obj.show_x_y(); return 0; } |
Constructor called 2 3
Time complexity: O(1)
Auxiliary Space: O(1)
Reasons to Define the Constructor Outside the Class
The following are some of the reasons why it is preferable to define constructors outside the class:
- No Compile-Time Dependency: One can put the class definition in the header file and the constructor definition in an implementation file that will be compiled.
- Readability and Cleaner Code: The main reason is to define the constructor outside the class is for readability. Since one can separate declarations into the header files and the implementations into the source files.
Example: GeeksForGeeks.h
C++
// Header file // Save this code with .h extension // For example- GeeksForGeeks.h #include <bits/stdc++.h> using namespace std; class ClassG { public : int a, b; // Constructor declaration ClassG(); // Function to print values void show() { cout << a << " " << b; } }; |
Time complexity: O(1)
Auxiliary Space: O(1)
File: geek.cpp
C++
// Adding GeeksForGeeks.h File #include"GeeksForGeeks.h" #include<bits/stdc++.h> using namespace std; // Constructor definition ClassG::ClassG() { a = 45; b = 23; } // Driver code int main() { // This will call the // constructor ClassG obj; // Function call obj.show(); } |
Output:
45 23
Time complexity: O(1)
Auxiliary Space: O(1)
Please Login to comment...