dimanche 28 juin 2020

C++: function calling order (inheritnce and methods)

I was asked to write the output of this code:

#include <iostream>
using namespace std;

class A {
    public:
    A() {}
    A(const A& a) {
         cout << "A copy ctor" << endl;
    }
    virtual ~A() {
         cout << "A dtor" << endl; 

    }
    virtual void type() const { 
        cout << "This is A" << endl; 

    }
};

class B: public A {
    public:
    virtual ~B() {
         cout << "B dtor" << endl; 
    }
    void type() const override {
         cout << "This is B" << endl; 
    }
};

A f(A a) {
    a.type();
    A a1();
    return a;
}

const A& g(const A& a) {
    a.type();
    return a;
}

int main() {
    A* pa = new B();
    cout << "applying function f:" << endl;
    f(*pa).type();
    cout << "applying function g:" << endl;
    g(*pa).type();
    delete pa;
    return 0;
}

I noticed something strange, on the third line in main() I expected to enter f(A a) by calling the copy C'tor, end the function, recive a copy of a (class A) (+) call the D'tor (class A) for the copy I passed to f(A a) and then return to the third line in main(), call type() (class A) and when I am done with the third line to call the D'tor (class A) again to earse the copy I got from f(A a).

What actually happend when I run the code was what I expected until (+) from there type() was immediately called and only then the D'tor was called for the copy that was passed and then for the copy recived.

It confused me and made me realise that I may not understand well the order of calls, I would like to recive an explanation (I tried searching for it online but could not find anything with methods involved).

thank you.

Aucun commentaire:

Enregistrer un commentaire