Reputation: 3461
So, this might be kinda of an embarrassing question. I was re-enforcing my C++ basics and I ran into this curious case.
The interesting part is that upon entering the function, the constructor is not called for the object lb but upon leaving the function the destructor is called for lb, I presume.
How could this be possible? Either both the constructor & destructor should be called when they enter the function. OR if only the destructor is being called then should lead to segmentation errors, I expect?
#include <iostream>
using namespace std;
class B {
public:
B() {
cout<<"Construct B"<<endl;
}
virtual ~B() {
cout<<"Destruct B"<<endl;
}
};
bool FuncByVal(B lb)
{
return true;
}
int main(int argc, char* argv[])
{
B b;
FuncByVal(b);
return 0;
}
And the output is: Construct B Destruct B Destruct B
I tested on Visual Studio 2012 under Windows 8.1 and Eclipse with MinGW under Windows 8.1.
Plus I tested under Linux (eclipse+gcc), as well, just to be sure.
p.s. for copy-by-reference the outputs were as I expected, i.e., only one constructor call and one destructor was called for the same code.
Upvotes: 2
Views: 141
Reputation: 114695
What's being called is the object's copy constructor, not its default constructor. Since you didn't define the copy constructor explicitly the compiler defined it implicitly (with no output of course).
class B {
public:
B() {
cout<<"Construct B"<<endl;
}
/// Add this
B(const B&) {
cout<<"Copy B"<<endl;
}
virtual ~B() {
cout<<"Destruct B"<<endl;
}
};
Upvotes: 5
Reputation: 302718
You are correct that a constructor for lb
will be called upon entering FuncByVal
. It's just the copy constructor, not the default constructor. Add this to your B
:
B(const B& ) {
cout << "Copy B\n";
}
And your code prints:
Construct B
Copy B
Destruct B
Destruct B
Upvotes: 4