2

I was in the process of trying out inheritance in c++ and tried to make a simple class:

    class Class
    :public int
    {

    };

But upon trying to compile I get the (visual studio 2013) error C3770 "'int' is not a valid base class. This error also occurs with other primitive types like bools chars and longs.

However using a user defined class wrapping class works fine:

template<typename T>
class Wrapper
{
    T Object;
        public:
            operator T&(){return Object;}
};

class Class
:public Wrapper<int>
{

};

My question is, is using primitive types directly as a base class illegal c++ or is it visual studio being difficult, or am I just plain doing inheritance wrong; I can't seem to find an answer anywhere.

user2628206
  • 241
  • 2
  • 11
  • 1
    Classes extend other classes. Int is not a class. – eddie_cat Jun 13 '14 at 21:00
  • This doesn't really make sense. How would you access the int value from a subclass? – pezcode Jun 13 '14 at 21:01
  • It's hard to say whether you're *doing* anything wrong; you're patently *wanting* something wrong, though. Inheritance is a very specific tool for a specific job, and much overused and overrated. A plain `int` member seems to be just fine. – Kerrek SB Jun 13 '14 at 21:18
  • the difference between class and primitive types is not only a C++ feature. e.g. your wrapper idea corresponds roughly to C# "boxing". as far as I know the fundamental issues were first identified and discussed by Barbara Liskov, in connection with what's now known as the "Liskov substitution principle". it's a pretty big issue. it connects to the old ellipse-versus-circle problem. – Cheers and hth. - Alf Jun 13 '14 at 21:34

1 Answers1

7

In C++, primitive types are not classes. Inheritance deals with classes. Naturally you cannot inherit a primitive type.

yizzlez
  • 8,757
  • 4
  • 29
  • 44