Why can't I inherit from int in C++?

前端 未结 19 2203
不知归路
不知归路 2020-12-02 18:24

I\'d love to be able to do this:

class myInt : public int
{

};

Why can\'t I?

Why would I want to? Stronger typing. For example, I

19条回答
  •  独厮守ぢ
    2020-12-02 18:51

    Why would I want to? Stronger typing. For example, I could define two classes intA and intB, which let me do intA+intA or intB+intB, but not intA+intB.

    That makes no sense. You can do all that without inheriting from anything. (And on the other hand, I don't see how you could possibly achieve it using inheritance.) For example,

    class SpecialInt {
     ...
    };
    SpecialInt operator+ (const SpecialInt& lhs, const SpecialInt& rhs) {
      ...
    }
    

    Fill in the blanks, and you have a type that solves your problem. You can do SpecialInt + SpecialInt or int + int, but SpecialInt + int won't compile, exactly as you wanted.

    On the other hand, if we pretended that inheriting from int was legal, and our SpecialInt derived from int, then SpecialInt + int would compile. Inheriting would cause the exact problem you want to avoid. Not inheriting avoids the problem easily.

    "Ints don't have any member functions." Well, they have a whole bunch of operators like + and -.

    Those aren't member functions though.

提交回复
热议问题