Constructor (C++)
A constructor is a special member function that runs automatically when an object is created. It has the same name as the class and is used to initialize the object's data.
C++
Constructors have no return type and can take parameters, letting you set up an object with specific starting values. A constructor with no parameters is called the default constructor.
Modern C++ favors a member initializer list (after a colon) to set members directly, which is more efficient than assigning to them inside the body.
Syntax
ClassName(parameters) : member(value) { /* body */ }Examples
C++
#include <iostream>
class Point {
public:
int x, y;
Point(int a, int b) : x(a), y(b) {}
};
int main() {
Point p(2, 5);
std::cout << p.x << " " << p.y << std::endl;
return 0;
}Output:
2 5