オブジェクトのスライスを使用したいコードのケースがありますが、それが安全か賢明かを判断しようとしています。これを判断するために、次の例を実行しました。
#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;
}
基本クラスが最上位 (ルート) ではないため、1 が返されることを期待していましたが、3 が表示されます。クラスのいずれかに仮想テーブルがある場合、あなたの答えはどのように変わりますか? 安全だと思わない場合、派生オブジェクトから非ルート ベース オブジェクトをコピーするための回避策はありますか?
次のコマンドを使用して、gcc 4.6.3 の Linux でこれを実行しました。
g++ -std=c++0x main.cc