C++

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

A constructor is a sort of member function that is responsible for initializing the objects in a class. It doesn’t have a return type, therefore you can’t use the return keyword, and it’s called automatically when the object is formed. 

  • The constructor is also used to solve the initialization problem. 
  • After the object has been constructed, it is called. 
  • The name is the same as the class.

Constructors

Constructors In C++, a constructor is a particular procedure that is run automatically when a class object is formed. 

Use the same name as the class, followed by parenthesis () to create a constructor: 

Example

class MyClass {     // The class

  public:           // Access specifier

    MyClass() {     // Constructor

      cout << “Hello World!”;

    }

};

int main() {

  MyClass myObj;    // Create an object of MyClass (this will call the constructor)

  return 0;

}

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

{

}

The Constructor Should Be Defined Outside of the Class for the Following Reasons 

The following are some of the reasons why constructors should be defined outside of the class: 

  • No Compile-Time Dependency: The class definition can be placed in the header file and the constructor definition in a built implementation file. 
  • Readability and Cleaner Code: The main rationale for defining the constructor outside the class is to make the code more readable. Because definitions and implementations can be separated into header files and source files.

C++

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

    }

};

C++

#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

RECOMMENDED ARTICLES





4 replies on “How to Define the Constructor Outside the Class in C++?”

  1. I’m often to blogging and i really appreciate your content. The article has actually peaks my interest. I’m going to bookmark your web site and maintain checking for brand spanking new information.

Leave a Reply

Your email address will not be published.