C++ dynamic_cast and static_cast use method examples

  • 2020-04-02 01:54:25
  • OfStack

First of all, dynamic_cast:


#include <iostream>
using namespace std;
class A{
    public:
        virtual ~A(){} //When using dynamic_cast, yes!
};
class B:public A{
    public:
        B(){
            m_b=12;
        }
        void foo(){
            cout<<"B: "<<m_b<<endl;
        }
    private:
        int m_b;
};
int main()
{    
    A *a=new B();
    B *b=dynamic_cast<B*>(a);
    b->foo();
    delete a;
    return 0;
}

There is no virtual ~A(){}, error is reported at compile time :(source type is not polymorphic).

Static_cast:


#include <iostream>
using namespace std;
class A{
    public:
        A():m_a(32){}
        void foo(){
            cout<<"A: "<<m_a<<endl;
        }
        void setA(int a){
            m_a=a;
        }
    private:
        int m_a;
};
class B:public A{
    public:
        B(){
            m_b=12;
            setA(13);
        }
        void foo(){
            cout<<"B: "<<m_b<<endl;
        }
    private:
        int m_b;
};
int main()
{    
    A *a=new B();
    B *b=static_cast<B*>(a);
    A *aa=static_cast<A*>(b);
    b->foo();
    aa->foo();
    delete a;
    return 0;
}

Print the addresses a, b and aa, and you can see that the addresses are the same.


Related articles: