클래스에서 사용하는 특별한 메서드(special method)로, 자동으로 객체를 생성한다. Constructor를 생성하기 위해서는 Class 이름뒤에 ()를 붙인다.
ex. ClassName()
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에 parameter를 주면, 값을 초기화하여 사용할 수 있다.
#include <iostream>
using namespace std;
class MyClass { // The class
public: // Access specifier
int height;
int width;
MyClass(int a, int b) { // Constructor
height=a;
width=b;
}
};
int main() {
MyClass myObj1(4, 6); // Constructor with Prarmeters
MyClass myObj2(5, 7);
// Print values
cout << myObj1.height << " " << myObj1.width << endl;
cout << myObj2.height << " " << myObj2.width << endl;
return 0;
}