How to generate a compiler warning/error when object sliced

后端 未结 8 1568
执笔经年
执笔经年 2021-02-04 03:58

I want to know if it is possible to let compiler issue a warning/error for code as following:

Note:

1. Yea, it is bad programming style and

8条回答
  •  感情败类
    2021-02-04 04:17

    I modified your code slightly:

    class Base{
      public:
        Base() {}
        explicit Base(const Base &) {}
    };
    
    class Derived: public Base {};
    
    void Func(Base)
    {
    
    }
    
    //void Func(Derived)
    //{
    //
    //}
    
    //main
    int main() {
      Func(Derived());
    }
    

    The explicit keyword will make sure that the constructor will not be used as an implicit conversion operator - you have to call it explicitly when you want to use it.

提交回复
热议问题