How to Define the Constructor Outside the Class in C++?
Last Updated :
23 Jul, 2022
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++
#include <iostream>
using namespace std;
class GeeksForGeeks {
public :
int x, y;
GeeksForGeeks( int , int );
void show_x_y() {
cout << x << " " << y << endl;
}
};
GeeksForGeeks::GeeksForGeeks( int a, int b)
{
x = a;
y = b;
cout << "Constructor called" << endl;
}
int main()
{
GeeksForGeeks obj(2, 3);
obj.show_x_y();
return 0;
}
|
Output
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++
#include <bits/stdc++.h>
using namespace std;
class ClassG {
public :
int a, b;
ClassG();
void show()
{
cout << a << " " << b;
}
};
|
Time complexity: O(1)
Auxiliary Space: O(1)
File: geek.cpp
C++
#include"GeeksForGeeks.h"
#include<bits/stdc++.h>
using namespace std;
ClassG::ClassG()
{
a = 45;
b = 23;
}
int main()
{
ClassG obj;
obj.show();
}
|
Output:
45 23
Time complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...