Search code examples
c++pointersmethodscallconstructor-overloading

Why and when is the overload constructor executed?


class A {
public:
    A(void) { cout << "A::A" << endl; }
    A(const A& a) { cout << "A::A(a)" << endl; }
    virtual ~A(void) { cout << "A::~A" << endl; }
    virtual void g(void) { cout << "A::g" << endl; }
};

class B : public A {
public:
    B(void) { cout << "B::B" << endl; }
    ~B(void) { cout << "B::~B" << endl; }
    void g(void){ cout << "B::g" << endl; }
};

void print(A c) {
    cout << "print" << endl;
}

int main(void) {
    A a;
    B b;
    A* c = &b;
    c->g();
    print(*c);
    return 0;
}

I don't understand why this statement A::A(a) get's executed when calling c->g() or print(*c);

And I'm not quite sure to which part of the programm does the Method print belongs to?


Solution

  • Print isn't a method, it's a function, as such it doesn't "belong" anywhere - it's simply part of your program. Functions are from the age before Object-Orientation, though still have an important place.

    The void print(A c) Function can be broken down as follows:

    1. void, this is the return value, in this case - nothing.
    2. print(, this is the name of the function.
    3. A c), this means it will take a single parameter of type A, named c.

    As such A::A(const A &) is the copy constructor of the object A; Essentially this method will be called Every time an object of type A is copied into a new object of type A

    When you call print(*c), you derefrence The pointer c, this results in a reference to the object pointed to by c (ie: an object of type A). This is then copy constructed into the print function, resulting in a temporary const A & that is used by the function.

    This is why the Copy-constructor is called.