dynamic_cast
• 실행시간 캐스팅 (overhead 有)
• 실제 가리키는 곳 조사해서 잘못되지 않는 경우 주소 반환
→ 잘못된 경우 「0」 반환
• porymorphic type 에 대해서만 사용 가능
→ 가상함수 없는 경우 컴파일 에러
[예제] downcasting
class Animal
{
public:
virtual ~Animal() {}
};
class Dog : public Animal {};
int main()
{
Animal* p = new Dog;
// error (암시적 형변환)
Dog* pd1 = pa;
// ok (명시적 형변환)
Dog* pd2 = static_cast<Dog*>(pa);
}
downcasting
• 기반 클래스 포인터 타입을 파생 클래스 포인터 타입으로 캐스팅
• 암시적 변환 될 수 없기에 명시적 캐스팅 필요
실행시간 overhead가 있기 때문에
타입이 확실한 경우에는 굳이 dynamic_cast 사용하지 않는 것 추천!
static_cast 주의사항
static_cast
• 컴파일 시간 캐스팅으로 실행시간 오버헤드 X
• 실제 메모리르 조사하지 않기 때문에 downcasting에서 잘못 될 수 있다.
→ 상속 관계 타입에서 항상 캐스팅 성공하는 문제
[예제]
class Animal
{
public:
virtual ~Animal() {}
};
class Dog : public Animal {};
class Cat : public Animal {};
int main()
{
Animal* pc = new Cat;
Dog* pd = static_cast<Dog*>(pc); // ?? -> ok 되서 문제
}
[예제] dynamic_cast
#include <iostream>
class Animal
{
public:
virtual ~Animal() {}
};
class Dog : public Animal {};
class Cat : public Animal {};
int main()
{
Animal* p1 = new Cat;
Dog* pd1 = dynamic_cast<Dog*>(p1);
std::cout << reinterpret_cast<void*>(pd1) << std::endl;
Animal* p2 = new Dog;
Dog* pd2 = dynamic_cast<Dog*>(p2);
std::cout << reinterpret_cast<void*>(pd2) << std::endl;
}
📌 [C++] static_cast 사용 방법 및 필요성
[C++] static_cast 사용 방법 및 필요성
static_cast 필요성C 언어에서도 type casing 가능하지만논리적으로 위험한 캐스팅을 대부분 허용해서개발자 의도 인지 실수 인지 구분하기 어렵다. [예제 코드]void* -> 다른 타입으로 캐스팅하는 것
zoosso.tistory.com
📌 [C++] reinterpret_cast 필요성 및 사용 방법
[C++] reinterpret_cast 필요성 및 사용 방법
reinterpret_castreinterpret_casttype_id>(expression);→ reinterpret_cast바꿀 타입>(대상); • 메모리 재해석 • 서로 다른 타입 주소 캐스팅 • 정수 ↔ 주소 사이 캐스팅 C++에서는 주로 static_cast 활용
zoosso.tistory.com
📌 [C++] 가상 함수 (virtual funciton)
[C++] 가상 함수 (virtual funciton)
가상 멤버 함수 (virtual function)동적 바인딩을 위해 사용class A{public: virtual void sub(void);}; [예제] 함수 재정의(overriding) 주의사항#include class Animal{public: void Cry() { std::cout Cry(); // ??? -> Dog? Animal?}Q) p-
zoosso.tistory.com
'프로그래밍 언어 > C++' 카테고리의 다른 글
[C++] 연산자 재정의 (Operator Overloading) (2) | 2025.03.05 |
---|---|
[C++] 다중 상속 (multiple inheritance) (2) | 2025.03.04 |
[C++] 인터페이스(Interface) (5) | 2025.03.02 |
[C++] object Slicing (1) | 2025.03.01 |
[C++] RTTI (Run-Time Type Information) (3) | 2025.02.28 |
댓글