I have a case in my code where I'd like to use object slicing, but I'm trying to determine if it's safe or smart to do it. In trying to determine this, I ran the following example:
#include <iostream>
using namespace std;
class Dog{
public:
Dog( int x )
:x{x}
{
};
int x;
};
class Spaniel: public Dog{
public:
Spaniel( int x, int y )
:Dog{x}, y{y}
{
}
int y;
};
class Green{
public:
Green( int q )
:q{q}
{
}
int q;
};
class GreenSpaniel: public Spaniel, public Green{
public:
GreenSpaniel( int x, int y, int q, int z )
:Spaniel{x,y}, Green{q}, z{z}
{
}
int z;
};
int main(){
GreenSpaniel jerry{ 1,2,3,4 };
Green fred = jerry;
cout << fred.q << endl; //correctly displays "3"
return 0;
}
I was expecting it to return 1 because the base class was not the top-most (root), but it displays 3. So, my question is why/how is it showing the correct answer and is this a safe practice? How would your answer change if any of the classes had virtual tables? If you don't consider it safe, do you have any workarounds for copying a non-root base object from a derived object?
I ran this in linux under gcc 4.6.3 with the following command:
g++ -std=c++0x main.cc