'C++' typeid

토스트·2025년 5월 12일
0

'C++' basic

목록 보기
32/35

<typeinfo>

typeid

C++에서 객체나 타입의 런타임 타입 정보를(RTTI, Run-Time Type Information) 가져올 때 사용하는 연산자입니다.
주로 다형성(polymorphism) 환경에서 실제 객체의 타입을 확인하는 데 사용됩니다.

객체나 타입에 대해 호출하여 해당 객체나 타입의 정보를 const std::type_info& 타입으로 반환합니다.

type_info : 런타임 타입 정보를 담고 있는 객체입니다.

class type_info {
public:
    type_info(const type_info& rhs) = delete; // cannot be copied
    virtual ~type_info();
    size_t hash_code() const;
    _CRTIMP_PURE bool operator==(const type_info& rhs) const;
    type_info& operator=(const type_info& rhs) = delete; // cannot be copied
    _CRTIMP_PURE bool operator!=(const type_info& rhs) const;
    _CRTIMP_PURE int before(const type_info& rhs) const;
    size_t hash_code() const noexcept;
    _CRTIMP_PURE const char* name() const;
    _CRTIMP_PURE const char* raw_name() const;
};

쉬운 예시

#include <iostream>
#include <typeinfo>

int main() {
    int x = 5;
    double y = 2.14;

    std::cout << typeid(x).name() << std::endl;
    std::cout << typeid(y).name() << std::endl;
    std::cout << typeid(char).name();

    return 0;
}

결과

typeid(ptr) | typeid(*ptr)

추상 클래스(Abstract class)

순수 가상 함수(pure virtual function)를 하나라도 가지고 있는 클래스입니다. 이러한 클래스는 인스턴스화할 수 없습니다.

추상 클래스를 오버라이딩하여 다형성을 구현했을 때, typeid(ptr)은 포인터 자체의 타입을 반환하고, typeid(*ptr)은 참조를 통해 실제 객체의 런타임 타입을 반환합니다.

  • typeid(ptr)은 ptr이 어떤 타입의 포인터인지를 나타냅니다. 포인터 변수 ptr이 가리키는 정적 타입(컴파일 타임 타입)을 반환합니다.

  • typeid(*ptr)은 ptr이 가리키는 실제 객체의 타입을 나타냅니다. *ptr은 ptr이 가리키는 객체를 참조하는 것이므로, 실제 객체의 런타임 타입이 반환됩니다.

예시

#include <iostream>
#include <typeinfo>

class Base {
public:
    virtual ~Base() {} // 가상 소멸자
};

class Derived : public Base {};

int main() {
    Base* b = new Derived();

    std::cout << typeid(b).name() << std::endl;
    std::cout << typeid(*b).name() << std::endl;   

    delete b;

    return 0;
}

컴파일 타임에 b의 타입은 Base*로 고정되어 있습니다. 하지만 실제로 b가 가리키는 런타임 객체는 Derived의 인스턴스입니다. 즉, b는 Derived 객체를 가리키는 Base 포인터입니다.

결과

  • typeid(b) : 포인터 자체의 타입을 보니 Base*
  • typeid(*b) : 객체에 대한 참조이므로, 이 때는 RTTI를 사용해서 실제 객체의 타입, 즉 Derived를 반환

0개의 댓글