LoginSignup
9
9

More than 5 years have passed since last update.

C++のスライシング

Last updated at Posted at 2013-03-24

C++忘備録1( http://qiita.com/items/702b8d3cd2491b0391e9 )を見て、スライシングの例を入れておいたほうが良いと思い。

slicing.cpp
#include <iostream>

using namespace std;

class Base {
public:
    virtual void print() const {   cout << "Base" << endl;    }
};

class Derived : public Base {
public:
    void print() const {  cout << "Derived" << endl;  }
};

void print_val(Base v)
{
   v.print();
}

void print_ref(Base & r)
{
    r.print();
}

int main()
{
    Base base;
    Derived derived;

    print_val(base); //=> Base
    print_val(derived); //=> Base : SLICING!
    print_ref(base); //=> Base
    print_ref(derived); //=> Derived

    return 0;
}

基底クラスの値を要求する関数に派生クラスの値を渡すと、スライシングという現象が起こる。
参照やコンスト参照なら問題にならない。スライシングが発生するのは値を要求する場合のみ。
スライシングはだいたいトラブルの原因にしかならないが、文法としてはなぜか OK なので、人間が注意する他ないと思う。
目安としては
「派生クラスを持つ型を値として要求しているとたぶん何かの間違い」
ということだと思う。

しかし。
トラックバックが欲しい。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9