How to Constructor defined outside the class in C++ ?
In C++, a constructor is a special member function of a class that is called automatically when an object of the class is created. By default, the constructor is defined inside the class. However, it is also possible to define a constructor outside the class. There are two ways to do this:
- Defining the constructor using the scope resolution operator (::)
Syntax:
ClassName::ConstructorName(parameters) {
// constructor code
}
Example:
#include <iostream>
using namespace std;
class MyClass {
public:
int x;
MyClass(int a);
};
MyClass::MyClass(int a) {
x = a;
cout << "Constructor called" << endl;
}
int main() {
MyClass obj(5);
cout << obj.x << endl;
return 0;
}
Output:
Constructor called
5
- Defining the constructor using a separate function
Syntax:
ClassName::ConstructorName(parameters);
ClassName::ConstructorName(parameters) {
// constructor code
}
Example:
#include <iostream>
using namespace std;
class MyClass {
public:
int x;
MyClass(int a);
};
MyClass::MyClass(int a) {
x = a;
cout << "Constructor called" << endl;
}
int main() {
MyClass obj(5);
cout << obj.x << endl;
return 0;
}
MyClass::MyClass(int a); // constructor declaration
MyClass::MyClass(int a) { // constructor definition
x = a;
cout << "Constructor called" << endl;
}
Output:
Constructor called
5