puzzlecracker wrote:
I think I saw some erratic results with different (some outdated)
compilers using a conventional inheritence model.
class A {
//details omitted
A(){...}
A(const A&){...}
operator=(const A &){...}
};
class B:A{
B(){...}
B(const B&){...}
operator=(const B &){...}
};
B b1;
B b2(b2); will the A copy constructor or A default constructor be
called prior to B copy constructor?
if B copy constructor is declared B(const B&)A(){...}
will both default and copy constructor of A be called?
same for overloaded operator - Does A's version of overloaded operator
is called as well?
What does your compiler(s) output when executing this code:
#include <iostream>
#include <ostream>
struct A
{
A()
{
std::cout << "A default\n";
}
A( const A & )
{
std::cout << "A copy\n";
}
A operator- ( const A & )
{
std::cout << "A operator -\n";
return * this;
}
};
struct B1 : A
{
B1()
{
std::cout << "B1 default\n";
}
B1( const B1 & )
{
std::cout << "B1 copy\n";
}
B1 operator- ( const B1 & )
{
std::cout << "B1 operator -\n";
return * this;
}
};
struct B2 : A
{
B2()
{
std::cout << "B2 default\n";
}
B2( const B2 & )
: A()
{
std::cout << "B2 copy\n";
}
B2 operator- ( const B2 & )
{
std::cout << "B2 operator -\n";
return * this;
}
};
struct B3 : A
{
B3()
{
std::cout << "B3 default\n";
}
B3( const B3 & b )
: A(b)
{
std::cout << "B3 copy\n";
}
B3 operator- ( const B3 & )
{
std::cout << "B3 operator -\n";
return * this;
}
};
template <typename X>
void f()
{
std::cout << "STEP a - construct\n";
X x;
std::cout << "STEP b - copy construct\n";
X x1( x );
std::cout << "STEP c - subtract\n";
x - x1;
std::cout << "DONE\n\n";
}
int main()
{
std::cout << "DO - A\n";
f<A>();
std::cout << "DO - B1\n";
f<B1>();
std::cout << "DO - B2\n";
f<B2>();
std::cout << "DO - B3\n";
f<B3>();
}
I believe the correct answer is this:
DO - A
STEP a - construct
A default
STEP b - copy construct
A copy
STEP c - subtract
A operator -
A copy
DONE
DO - B1
STEP a - construct
A default
B1 default
STEP b - copy construct
A default
B1 copy
STEP c - subtract
B1 operator -
A default
B1 copy
DONE
DO - B2
STEP a - construct
A default
B2 default
STEP b - copy construct
A default
B2 copy
STEP c - subtract
B2 operator -
A default
B2 copy
DONE
DO - B3
STEP a - construct
A default
B3 default
STEP b - copy construct
A copy
B3 copy
STEP c - subtract
B3 operator -
A copy
B3 copy
DONE