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

前端 未结 19 2245
不知归路
不知归路 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:35

    Int is an ordinal type, not a class. Why would you want to?

    If you need to add functionality to "int", consider building an aggregate class which has an integer field, and methods that expose whatever additional capabilities that you require.

    Update

    @OP "Ints aren't classes" so?

    Inheritance, polymorphism and encapsulation are keystones of object oriented design. None of these things apply to ordinal types. You can't inherit from an int because it's just a bunch of bytes and has no code.

    Ints, chars, and other ordinal types do not have method tables, so there's no way to add methods or override them, which is really the heart of inheritance.

提交回复
热议问题