Here's code that produces different output in g++ 4.7 and vs2012 (cl17).
#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "1" << endl; }
~A() { cout << "2" << endl; }
};
class B : public A
{
public:
B() { cout << "3" << endl; }
~B() { cout << "4" << endl; }
};
void func(A a) {}
int main()
{
B b;
func(b);
return 0;
}
The GCC output is 13242
, while cl outputs 132242
.
Why does the cl compiler produce a second A
object while it makes a copy on the stack, and for what purpose?
It seems to be a compiler bug.
The C++ Standard does not use the term Object Slicing, You are passing an object of the type B
to a function which receives an parameter of the type A
. The compiler will apply the usual overload resolution to find the appropriate match. In this case:
The Base class A
has compiler provided copy constructor, which will take a reference to A
and in absence of other conversion functions this is the best match and should be used by the compiler.
Note that if better conversion was available, it would be used. For eg: If A
had a constructor A::A( B const& )
, in addition to the copy constructor, then this constructor would be used, instead of the copy constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With