what's polymorphic type in C++?

前端 未结 5 1259
猫巷女王i
猫巷女王i 2021-02-01 14:56

I found in one article saying \"static_cast is used for non-polymorphic type casting and dynamic_cast is used for polymorphic type casting\". I understand that int and double ar

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-01 15:24

    static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided.

    static_cast can also be used to perform any other non-pointer conversion that could also be performed implicitly, like for example standard conversion between fundamental types:

    double d=3.14159265;
    int i = static_cast(d); 
    

    dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

    Therefore, dynamic_cast is always successful when we cast a class to one of its base classes.

    // dynamic_cast
    #include 
    #include 
    using namespace std;
    
    class CBase { virtual void dummy() {} };
    class CDerived: public CBase { int a; };
    
    int main () {
     try {
        CBase * pba = new CDerived;
        CBase * pbb = new CBase;
        CDerived * pd;
    
        pd = dynamic_cast(pba);
        if (pd==0) cout << "Null pointer on first type-cast" << endl;
    
        pd = dynamic_cast(pbb);
        if (pd==0) cout << "Null pointer on second type-cast" << endl;
    
        } catch (exception& e) {cout << "Exception: " << e.what();}
        return 0;
     }
    

    Compatibility note: dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types . Some compilers support this feature as an option which is disabled by default. This must be enabled for runtime type checking using dynamic_cast to work properly.

    Virtual Functions are responsible for Run-time Polymorphism in C++. A class that has at least one virtual function has polymorphic type.

    Read More....

    Read this too. It has been clearly written thatA class that declares or inherits a virtual function is called a polymorphic class.

提交回复
热议问题