객체나 값의 자료형을 명시적으로 변환하는 기능이다.
전통적인 C 스타일 캐스팅과 C++ 스타일 캐스팅으로 나눌 수 있다.
(변환할 타입) 변수명
예시:
int a = 10;
double b = (double)a; // C 스타일 캐스팅
static_castint → float).사용 예시:
float f = 3.14f;
int i = static_cast<int>(f);
dynamic_castBase 클래스에 반드시 virtual 함수가 필요.nullptr 반환.사용 예시:
class CTest_A {
public:
virtual ~CTest_A() {
printf("CTest_A 소멸 \n");
}
};
class CTest_B : public CTest_A {
public:
virtual ~CTest_B() {
printf("CTest_B 소멸 \n");
}
int b = 0;
};
class CTest_C : public CTest_A {
public:
virtual ~CTest_C() {
printf("CTest_C 소멸 \n");
}
int c = 1;
int d = 2;
};
CTest_A* temp = new CTest_B();
CTest_B* tempB = dynamic_cast<CTest_B*>(temp); // 캐스팅 가능
CTest_C* tempC = dynamic_cast<CTest_C*>(temp); // 캐스팅 불가 → nullptr
const_castconst, volatile 등의 한정자만 추가/제거 가능.const로 선언된 객체를 수정하면 예상하지 못하는 동작이 발생할 수 있음 → 주의 필요.사용 예시:
const int x = 10;
int* px = const_cast<int*>(&x);
*px = 20; // 정의되지 않은 동작: 원래 const 객체는 수정 불가
reinterpret_cast사용 예시:
int a = 10;
void* ptr = reinterpret_cast<void*>(&a);
int* intPtr = reinterpret_cast<int*>(ptr);
C++에서 런타임에 객체의 실제 타입 정보를 얻을 수 있는 기능이다.
가상 클래스(virtual 함수가 있는 클래스)에만 적용 된다.
대표 기능
1. typeid : 타입에 대한 id => typeinfo 헤더를 추가해야 사용 가능
2. type_info : 타입에 대한 정보 (클래스 명)
3. dynamic_cast : 캐스팅 수행 정보
동적 캐스팅을 할 때 실제로 hashing된 id로 RTTI가 캐스팅 체크를 해준다.
두 객체의 hash id를 비교해 같으면 캐스팅 성공이 되고 다르면 실패(nullptr 또는 예외)가 된다.