이번 포스트는 이전의 상속의 개요부터 다시 시작합니다.
class Base{
};
class Derived : access - specifier Base { // 왼쪽 : Deirved class , 오른 쪽 : Base class
};
access - specifier : public, private, protected 등과 같이 접근 권한을 의미
#include <iostream>
class Entity {
protected: // 새롭게 배울 접근 제한자
int x;
int y;
public:
Entity(int x , int y)
: x{x},y{y}{}
void showPosition()
{
std::cout << "[" << x << "," << y << "]" << std::endl;
}
void Talk()
{
std::cout << "Hello." << std::endl;
}
};
class Player : public Entity {
private:
int hp, xp, speed;
public:
Player(int x , int y ,int speed)
: hp{x},xp{y},speed{speed}{}
void Move(int dx, int dy)
{
x += dx;
y -= dy;
}
};
int main()
{
Entity e{ 1,1 };
e.showPosition();
e.Talk();
Player p{1,1,1};
p.Move(2, 2);
///// Entitiy를 상속을 받았기 때문에 사용이 가능하다.
p.showPosition();
p.Talk();
return 0;
}
Base class에서 접근 가능
Derived Class에서 접근 가능
기본 또는 유도 클래스의 “객체”로부터는 접근 불가능!
#include <iostream>
class Entity {
protected:
int x;
int y;
public:
Entity() = default;
Entity(int x , int y)
: x{x},y{y}{}
void showPosition()
{
std::cout << "[" << x << "," << y << "]" << std::endl;
}
void Talk()
{
std::cout << "Hello." << std::endl;
}
};
class Player : public Entity {
private:
int hp, xp, speed;
public:
Player(int x , int y ,int speed)
: hp{x},xp{y},speed{speed}{}
void Move(int dx, int dy)
{
//Entity의 x,y에 접근이 가능하다.
x += dx;
y -= dy;
}
void setHp(int hp)
{
this->hp = hp;
}
};
int main()
{
Entity e{ 1,1 };
e.showPosition();
e.Talk();
Player p{1,1,1};
p.Move(2, 2);
///// Entitiy를 상속을 받았기 때문에 사용이 가능하다.
p.Move(-1, -2);
p.showPosition();
p.Talk();
return 0;
}
class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived : public Base
{
};
int main()
{
Derived d;
d.a = 10; // a 만 public이기 때문에 객체 접근이 가능함
std::cout << sizeof(int) << std::endl; // 4 byte
std::cout << sizeof(Base) << std::endl; // 12 byte (int 변수가 4개)
std::cout << sizeof(Derived) << std::endl; // 12 byte (int 변수가 4개)
}
d.b, d.c와 같이 직접 객체에 접근이 불가능 하지만 메모리에 올라가 있지 않은 것은 아니다!
유도 클래스는 기본 클래스의 멤버를 포함하므로, 유도 클래스가 초기화 되기 이전에 기본 클래스에서 상속된 부분이 반드시 초기화 되어야 함
유도 클래스 객체가 생성될 때
class Base
{
public:
Base() {
std::cout << "Base 생성자 생성 " << std::endl;
}
};
class Derived : public Base
{
public:
Derived() {
std::cout << "Derived 생성자 생성" << std::endl;
}
};
int main()
{
Derived d;
}
위의 코드를 실행 해보면 Base class의 생성자가 호출이 된다.
소멸자는 생성자와 반대 순서로 호출됨
즉, 유도 클래스가 소멸될 때,
유도 클래스는 기본 클래스의 생성자, 소멸자 및 오버로딩된 대입 연산자를 상속하지 않음
대신 , 기본 클래스의 생성자, 소멸자 및 오버로딩된 대입 연산자를 유도 클래스로부터 호출이 가능함