| 개념 | 설명 |
|---|---|
| 상속(Inheritance) | 부모 클래스의 속성과 메서드를 자식 클래스가 물려받는 개념 |
| 은닉성(Encapsulation) | 객체 내부의 데이터를 외부에서 직접 접근하지 못하게 하는 개념 |
| 다형성(Polymorphism) | 같은 인터페이스를 가진 객체가 다양한 동작을 수행할 수 있도록 하는 개념 |
📌 상속(Inheritance)을 사용하면 코드의 재사용성과 유지보수성을 높일 수 있습니다.
Player, Knight, Mage 클래스)#include <iostream> // 입출력 기능 제공
using namespace std; // std:: 생략
#include <iostream> : cout, cin을 사용하기 위해 포함 using namespace std; : std::cout 대신 cout으로 사용 가능 Player (부모 클래스)class Player
{
public:
Player()
{
_hp = 0;
_attack = 0;
_defence = 0;
cout << "Player() 기본 생성자 호출" << endl;
}
Player(int hp)
{
_hp = hp;
_attack = 0;
_defence = 0;
cout << "Player(int hp) 생성자 호출" << endl;
}
~Player()
{
cout << "~Player() 소멸자 호출" << endl;
}
void Move() { cout << "Player Move 호출" << endl; }
void Attack() { cout << "Player Attack 호출" << endl; }
void Die() { cout << "Player Die 호출" << endl; }
public:
int _hp;
int _attack;
int _defence;
};
📌 Player 클래스
Player()를 호출하면 HP, 공격력, 방어력을 0으로 설정Player(int hp)를 호출하면 HP만 초기화하고 나머지는 0으로 설정~Player()를 호출하면 "Player 소멸자 호출" 메시지를 출력Move() : 이동 메시지 출력Attack() : 공격 메시지 출력Die() : 죽음 메시지 출력Knight (자식 클래스 - Player 상속)class Knight : public Player
{
public:
Knight()
{
_stamina = 100;
cout << "Knight() 기본 생성자 호출" << endl;
}
Knight(int stamina) : Player(100)
{
_stamina = stamina;
cout << "Knight(int stamina) 생성자 호출" << endl;
}
~Knight()
{
cout << "~Knight() 소멸자 호출" << endl;
}
// 부모의 Move()를 재정의
void Move() { cout << "Knight Move 호출" << endl; }
public:
int _stamina;
};
📌 Knight 클래스 (Player 상속)
class Knight : public PlayerPlayer 클래스를 Knight가 상속받음_stamina를 100으로 초기화Player(100)을 호출하여 HP를 100으로 초기화하고, _stamina를 설정"~Knight() 소멸자 호출" 메시지 출력Move() : 부모 클래스의 Move()를 재정의하여 "Knight Move 호출" 메시지 출력Mage (자식 클래스 - Player 상속)class Mage : public Player
{
public:
int _mp;
};
📌 Mage 클래스 (Player 상속)
class Mage : public PlayerPlayer 클래스를 Mage가 상속받음_mp (마나 포인트)main() 함수 - 객체 생성 및 사용int main()
{
Knight k(100);
k._hp = 100;
k._attack = 10;
k._defence = 5;
k._stamina = 50;
k.Move(); // 자식이 재정의한 Move 호출
k.Player::Move(); // 부모의 Move 호출
k.Attack();
k.Die();
return 0;
}
📌 출력 예시
Player(int hp) 생성자 호출
Knight(int stamina) 생성자 호출
Knight Move 호출
Player Move 호출
Player Attack 호출
Player Die 호출
Knight() 소멸자 호출
Player() 소멸자 호출
📌 실행 흐름
1. Knight k(100); 생성
Player(int hp) 호출 → "Player(int hp) 생성자 호출"Knight(int stamina) 호출 → "Knight(int stamina) 생성자 호출"k.Move(); → "Knight Move 호출"k.Player::Move(); → "Player Move 호출"k.Attack(); → "Player Attack 호출"k.Die(); → "Player Die 호출"~Knight() 호출 → "Knight() 소멸자 호출"~Player() 호출 → "Player() 소멸자 호출"| 객체 생성 시 호출 순서 | 객체 소멸 시 호출 순서 |
|---|---|
| 부모 생성자 → 자식 생성자 | 자식 소멸자 → 부모 소멸자 |
📌 왜 이렇게 호출될까?
Player 생성자 변경하기Knight(int stamina) : Player(100)
Player(100)을 호출하여 기본 생성자가 아닌 특정 생성자를 호출 가능:) 사용✅ 코드 재사용성: 부모 클래스에서 정의한 기능을 재사용하여 중복 코드 방지
✅ 유지보수 용이성: 부모 클래스만 수정하면 자식 클래스에 자동 반영
✅ 계층적 구조 표현: 현실 세계의 관계를 코드로 표현 가능