How to generate a compiler warning/error when object sliced

后端 未结 8 1563
执笔经年
执笔经年 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:16
    class Derived: public Base{};
    

    You're saying Derived IS a Base, and so it should work in any function that takes a base. If this is a real problem, maybe inheritance isn't what you really want to be using.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题