lundi 26 juin 2017

Output coming from virtual class

I have a C++ test next Tuesday about virtual types, inheritance, etc. My issue is that I have a strange output coming from my code, and I don't have a clue where is it coming from:

Code:

#include <iostream>
#include <typeinfo>

using std::cout; using std::endl;

template<int id> class B{
    int* p;

public:
    B(): p{new int}{
        cout << typeid(*this).name() << "::" << typeid(*this).name() << "()" << endl;
    }

    B(const B& b): p{new int{*(b.p)}}{
        cout << typeid(*this).name() << "::" << typeid(*this).name() << "(const " << typeid(*this).name() << "&)" << endl;
    }

    virtual ~B(){
        delete p;
        cout << typeid(*this).name() << "::~" << typeid(*this).name() << "()" << endl;
    }
};

class D: public B<0>{

public:
    D(){
        cout << "D::D()" << endl;
    }

    D(const D& d): B<0>{static_cast<const B&>(d)}, b1{d.b1}, b2{d.b2}{
        cout << "D::D(const D&)" << endl;
    }

    ~D(){
        cout << "D::~D()" << endl;
    }

private:

    B<1> b1;
    B<2> b2;
};

int main()
{
    B<0>& b{*new D};
    cout << "-----------------------------" << endl;
    D d{dynamic_cast<D&>(b)};
    cout << "-----------------------------" << endl;
    delete &b;
    cout << "-----------------------------" << endl;
}

Output:

1BILi0EE::1BILi0EE()
1BILi1EE::1BILi1EE()
1BILi2EE::1BILi2EE()
D::D()
-----------------------------
1BILi0EE::1BILi0EE(const 1BILi0EE&)
1BILi1EE::1BILi1EE(const 1BILi1EE&)
1BILi2EE::1BILi2EE(const 1BILi2EE&)
D::D(const D&)
-----------------------------
D::~D()
1BILi2EE::~1BILi2EE()
1BILi1EE::~1BILi1EE()
1BILi0EE::~1BILi0EE()
-----------------------------
D::~D()
1BILi2EE::~1BILi2EE()
1BILi1EE::~1BILi1EE()
1BILi0EE::~1BILi0EE()

Questions:

1) Why are the names from each typeid so strange? Is there a way to calculate each one? I figured out that if I change my compiler the names change aswell.

2) Why is my program printing twice the output from my destructor from B base class. Is it related with virtual type and inheritance?

3) Can somebody explain me the benefits of using static_cast instead dynamic_cast? From every perspective I have been taught, static_cast usually have more problems in execution time vs dynamic_cast.

Thank you a lot.

Aucun commentaire:

Enregistrer un commentaire