0
#include <iostream>

using namespace std;
class cls1 {

protected:
    int x;
public:
    cls1() {
        x = 13;
        cout << "Constructor for cls1 was called\n";
    }
};
class cls2 : public cls1 {
    int y;
public:
    cls2() {
        y = 15;
        cout << "Constructor for cls2 was called\n";
    }
    int f(cls2 ob) {
        return (ob.x + ob.y);
    }
};
int main()
{
    cls2 ob;
    cout << ob.f(ob);
    return 0;
}

The code above prints:

constr1
constr2
28

Why isn't the constructor for cls2 called twice since, in the function f, the object is passed by value instead of reference, meaning a new temporary object is created?

Diana
  • 363
  • 2
  • 8
  • 4
    You need to log from the copy-constructor as well, since `f::ob` is copy-initialized from `main::ob`. – Quentin Jan 29 '20 at 16:12
  • Does this answer your question? [What's the difference between passing by reference vs. passing by value?](https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value) – Philippe B. Jan 29 '20 at 16:13
  • this is very much related, but not up-to-date for C++11 anymore: https://stackoverflow.com/questions/28716209/what-operators-do-i-have-to-overload-to-see-all-operations-when-passing-an-objec (actually the answer does take into account C++11) – 463035818_is_not_an_ai Jan 29 '20 at 16:14
  • actually it makes a good duplicate... – 463035818_is_not_an_ai Jan 29 '20 at 16:16

0 Answers0