클래스 생성자는 해당 클래스의 새 객체를 생성할 때마다 실행되는 클래스의 특수 멤버 함수입니다.
생성자는 클래스와 정확히 같은 이름을 가지며 반환 유형이 전혀 없으며 심지어 void도 없습니다. 생성자는 특정 멤버 변수의 초기 값을 설정하는 데 매우 유용할 수 있습니다.
다음 예제는 생성자의 개념을 설명합니다 -
예시
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void) {
cout << "Object is being created" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
// Main function for the program
int main() {
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
} 출력
Object is being created Length of line : 6