Home > Software engineering >  strange behavior of C downcasting on object
strange behavior of C downcasting on object

Time:11-08

i ran the code below to assign parent portion of objet to child object. but as described inline, c style downcast behaves something unexpected. what happen there? please refer to the comment below.

    struct A {
    public:
        int i{};
        A() { std::cout<<"A constructor called\r\n"; }
        ~A() { std::cout<<"A destructor called\r\n"; }
    };

    struct B : public A {
        B() { std::cout<<"B constructor called\r\n"; }
        ~B() { std::cout<<"B destructor called\r\n"; }
    };

    A a{};
    B b{};
    a.i = 1;
    (A)b = a;  // this code no effect and surprisingly the destructor of A is called.
               // there was no compiler warning (g   (Ubuntu 11.2.0-7ubuntu2) 11.2.0)
    std::cout<<a.i<<std::endl;
    std::cout<<b.i<<std::endl;
    A& ra = b;
    ra = a;     // A portion of B is initialized as expected
    std::cout<<b.i<<std::endl;

this code prints as

A constructor called
A constructor called
B constructor called
A destructor called <-- please note here
1
0
1
B destructor called
A destructor called
A destructor called

CodePudding user response:

magic is here: (A)b = a;

what happend is:

  1. call A's copy constructor and create a new [class A object]. it's a temporary object, and it's destoryed after this statement. so print [A destructor called <-- please note here]
  2. call A's operator= on the temporary object. it's only effect the temporary object instead of original b;
  • Related