I’m working on some project, and need some simple advice.
I have one base class, and 6 classes derived from that base.
5 of those 6 derived classes should have two private int, but the 6th needs just one private int. And of course member functions get() and set() for both ints (6th one just get() and set() for only one int).
My question is: Should I have a base class with two ints and set() and get() functions or should I have a base class with one int and set() and get() for that int, and all others derived classes(except the 6th) with one more int and two more methods?
The answer to your question depends on what do the different classes model and what do the
intdata members mean. Let’s assume that your derived classes should really inherit from the base class (and this is a big assumption). I also assume that we are talking about public inheritance here.For sure, the base class must not contain both
intdata members. If your hierarchy is correct, the second member is only meaningful for some objects of this class (specifically, it is meaningless for objects of your 6th class). Remember that public inheritance models an IS-A relationship: all parts of your base class must also apply to all your derived classes.Now for the first data member. Does it mean the same in all your derived classes? Will it also mean the same for any other derived class you could conceivably have? Should all objects of your base class have this member? If so, it should appear in the base class.
The most important thing here is to have a good design with correct inheritance. If you have that, then the answer to your questions is trivial. If you don’t, the answer is immaterial because you have to fix your design first.