1

I have the following project, in which I define a main class called frame, and from that class I derive multiple type of classes. The main class "frame" has a protected variable defined as:

class frame {
protected:
    char header[4];
}

And in the derived classes I want the array header to have different size, as the following:

class dervied_frame : public frame {
protected:
    char header[8];
}

So my question is it possible to override the protected variable in the derived classes? and how to do that?

Note: I don't want to define the header as a pointer and in then in the constructor I define the size that I want through dynamic allocation.

IoT
  • 607
  • 1
  • 11
  • 23

1 Answers1

3

You could use a template like this:

template <int headerSize>
class frame {
protected:
    char header[headerSize];
};

class dervied_frame : public frame<8> {
};

But then every sub-class will have a unique base class so you won't really be able to do anything with a frame *. Depending on what you are using this class for, that restriction could be a deal breaker. You can partially get around this by adding another super-class:

class frame {
public:
    void otherMethodsHere();
};

template <int headerSize>
class frameHeader : public frame {
protected:
    char header[headerSize];
};

class dervied_frame : public frameHeader<8> {
};
IronMensan
  • 6,761
  • 1
  • 26
  • 35