생성자(Constructor)
객체가 만들어질 때 자동으로 호출되는 함수. 내가 직접 호출하기도 하고(명시적 호출), 컴파일러가 호출하기도 합니다.(암시적 호출)
// 컴파일 되기 전.
class Human
{
// 분명 비워뒀습니다.
};
// 컴파일 된 후. 다음과 비슷하게 흘러갑니다.
class Human
{
Human() {}; // 기본 생성자가 자동으로 만들어지게 됩니다.
};
클래스에 생성자가 없으면 컴파일러가 시본 생성자를 자동적으로 만들어 줌.
기본 생성자는 매개변수 X
오버로딩
같은 이름이지만 매개변수 목록은 다르게 함수를 재정의하는 것.
이를 생성자 오버로딩이라고 한다.
Human(); // 생성자
Human(float InHeight, float InWeight); // 생성자 오버로딩. 매개변수 목록이 달라집니다.
Human Park(180.0f, 68.0f); // 매개변수 목록이 "최대한" 일치하는 생성자가 자동으로 호출됩니다.
예시코드
// Human.h
#pragma once
class Human
{
public:
Human();
Human(float InHeight, float InWeight, int InBirthDay);
private:
float Height;
float Weight;
const int BirthDay;
};
// Human.cpp
#include "Human.h"
#include <iostream>
using namespace std;
Human::Human()
: Height(0.0f)
, Weight(0.0f)
, BirthDay(20260101)
{
cout << "Human() constructor has been called." << endl;
}
Human::Human(float InHeight, float InWeight, int InBirthDay)
: Height(InHeight)
, Weight(InWeight)
, BirthDay(InBirthDay)
{
cout << "Human(float InHeight, float InWeight, int InBirthDay) constructor has been called." << endl;
}
// Main.cpp
#include <iostream>
#include "Human.h"
int main(void)
{
Human Human1;
Human Human2 = Human(175.4f, 72.2f, 18900304);
Human* Human3 = new Human();
Human* Human4 = new Human(161.5f, 48.0f, 19900202);
delete Human3;
Human3 = nullptr;
delete Human4;
Human4 = nullptr;
return 0;
}
출력 순서
Human() constructor has been called.
Human(float InHeight, float InWeight, int InBirthDay) constructor has been called.
Human() constructor has been called.
Human(float InHeight, float InWeight, int InBirthDay) constructor has been called.
'C++' 카테고리의 다른 글
| 2026-6-1 코드카타 (0) | 2026.06.01 |
|---|---|
| STL (0) | 2026.03.24 |
| 생성자와 소멸자 (0) | 2026.03.12 |
| C++로 전직 시스템과 전투 시스템 구현해보기 (0) | 2026.03.10 |
| Class (0) | 2026.03.09 |