howtechstuffworks howtechstuffworks - 8 months ago 35
C++ Question

How to Avoid Duplicate copies of Base Class Members in Derived Class in C++

In my project, there is one Base class and there are 3 different derived classes. I have some macro variables written as const int in the base class. All the derived member is going to access these members and are going to see the same value. Since, its a const, and it is not going to change, maintaining 3 different values will be waste of space. Hence I want a way to maintain just one copy of base class const members so that all the derived class will use the same.


Class Base {

const int ZER0;
const int ONE;

class Derived1:public Base {
int some_method1();


int Derived1::some_method1() {

int value = ZERO;


class Derived2:public Base {
int some_method2();


int Derived2::some_method2() {
int value = ONE;


Derived1 d1;

Derived d2;

//Here in both the methods the values are constant, but still the ZERO and ONE are going to have different space. Is there a way, where I maintain only one copy? I could think of static variable. Is it okay to use static inside class and where do I initialize the static variable. Please advice.

PS: This questions might be a duplicate, but I cant find something with similar words, if you feel this is, please feel free to redirect to the corresponding article/question;


If I'm understanding you correctly, would an enum do what you're looking for?

class Base