Skip to content
Related Articles

Related Articles

How to Define the Constructor Outside the Class in C++?

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 01 Apr, 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++




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

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

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!