I am working on a project for an Arduino-based sytem (i.e. an embedded system) and have a limited amount of ROM for code to live in.
I have found myself needing several different types of collection classes (e.g List
, Stack
, Queue
).
After writing these I noticed that aside from the features that make them behave differently (e.g. Add
vs Push
vs Enqueue
, Pop
vs Dequeue
) they share a lot of common functionality (e.g. they have the exact same fields).
This got me thinking, if I were to create a base class that contained all of the common functionality of the other classes (let's call it Collection
) and made the other classes inherit from it, and have them implement only the functionality that differs, would that result in less compiled code?
I'm expecting that it will because the child classes can all refer to the parent's implementations of the common functions, but I could be wrong so I'd rather ask before I attempt this change.
Ok, to clarify this further since people seem to be misinterpreting, consider these hypothetical classes:
class A
{
protected:
int value;
public:
void assign(int other)
{
this->value = other;
}
}
class B : public A
{
public:
void assignAdd5(int other)
{
this->value = other + 5;
}
}
And then the code:
A a = A();
B b = B();
a.assign(4);
b.assign(4);
I am expecting that assign
refers to the same method in both cases (and thus the same compiled block of code) despite the different types because B
is a subclass of A
. If this is the case then having classes with similar functionality all inherit from a single base class implementing the similarities would produce less compiled code than making each class implement the functionality separately because each child class would be using the same function.
The information I provided regarding the situation that prompted this question was merely background, I am in whether this is the case with any compiler, not just the one I'm using (and I fully appreciate that the answer may be "it's possible that some compilers do this, but not all of them do", and that's a perfectly acceptable answer).