Classe Constructor

Hi All,

When I run this code it prints one X. That is when u is defined as a variable of type Uno. What I'm wondering is why there is no X printed when e is defined as a variable of type Uno? It does so when I change the function to:

Uno e;
e = d;

Hope anyone can help....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  #include <iostream>

using std::cout;
using std::cin;

class Uno {
public: Uno() {
    cout << "X";
    }
};

Uno foo(Uno d){
    Uno e = d;
    return e;
}

int main(){
    Uno u;
    foo(u);
    return 0;
}
Maybe that this behavior is due to your compiler's optimizing process. I compiled and ran your code with your claimed changes at cpp.sh and there I got 'XX'.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using std::cout;
using std::cin;

class Uno {
public: Uno() {
    cout << "X";
    }
};

Uno foo(Uno d){
    Uno e;
    e = d;
    return e;
}

int main(){
    Uno u;
    foo(u);
    return 0;
}

Compile and run this by clicking on the gearwheel at right beside the code window, and you will get two X.
Last edited on
rob: you're not running the same program as OP, specially your lines 13-14 vs OP line 13. OP code at shell gives single X: http://cpp.sh/3rm7f. guess why?
Yes, it's not the same version then the OP's posted code . But i interpreted the OP's text in such manner that he at first tried a code example like mine whereby he would missing a second X. And I think that a single X at the OP's posted code is correct behavior. Think you that's not the case?
Last edited on
When you declare Uno u; your are invoking the... how can I call it?... ‘normal’ constructor, which prints an ‘X’ on the screen.
When you declare Uno e = d; you are invoking the copy constructor, which you haven’t defined, so it’s automatically provided by the compiler to perform the basic copy operations.

If you add a copy constructor, you can see when it’s invoked:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using std::cout;
using std::cin;

class Uno {
public: Uno() {
    cout << "X";
    }
    Uno(Uno& other)
    {
        std::cout << "Copy constructor invoked\n";
    }
};

Uno foo(Uno d){
    std::cout << "\nJust entered foo(Uno d) --> ";
    Uno e = d;
    return e;
}

int main(){
    Uno u;
    foo(u);
    return 0;
}



XCopy constructor invoked

Just entered foo(Uno d) --> Copy constructor invoked

The copy constructor is invoked twice, the first time when you call foo(u); from inside main(), because you pass a copy of ‘d’, and another one from the instruction Uno e = d; inside foo().
Last edited on
Thank you very much. It is indeed the copy constructor that I was missing.

Now when I'm changing the function so that d is passed by ref

Uno foo(Uno &d)

The copy constructor is only passed once.
Topic archived. No new replies allowed.