Idiomatic way to prevent slicing?

后端 未结 3 2063
执笔经年
执笔经年 2021-02-07 07:09

Sometimes it can be an annoyance that c++ defaults to allow slicing. For example

struct foo { int a; };
struct bar : foo { int b; };

int main() {
    bar x{1,2         


        
3条回答
  •  旧巷少年郎
    2021-02-07 07:39

    You can prevent the base from being copied outside of member functions of derived classes and the base itself by declaring the copy constructor protected:

    struct foo {
        // ...
    protected:
        foo(foo&) = default;
    };
    

提交回复
热议问题