Open In App

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 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++ 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;
}

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:

Example: GeeksForGeeks.h




// 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




// 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)


Article Tags :
C++