quick question on declaring functions. Lets say I have the following code:
class a{
int var;
/* stuff*/
}
class b : a{
/* other stuff*/
}
class c : a{
/* more other stuff*/
}
class d{
myFunctionThatWantsTheIntNamedVar(SubClassOfClassA SomeClassUnknownAtCompileTime);
}
and myFunctionThatWantsTheIntNamedVar() wants just that, the integer(called var) declared in the base class of a. The function in class d may be passed an instance of class b or class c, which is not known at compile time (only at run time).
Is there a way I can concisely declare a function that could take either class b or c and get that same base variable?
What I have done in the mean time is declare two methods in class d, as follows:
class d{
myFunctionThatWantsTheIntNamedVar(c aClassCInstance);
myFunctionThatWantsTheIntNamedVar(b aClassBInstance);
}
which is fine and all, but the code in the two methods is IDENTICAL… And from my understanding of object oriented programming, if the code is identical you should be able to combine it into a better function.
Any thoughts on this? Just looking for best practices or other advice here, as I work at a small company and getting feedback can be hard at times.
EDIT: sorry, I had an error in my code, changed it from:
myfunctionThatWantsTheInNamedVar(a aClassAInstance);
to:
myfunctionThatWantsTheInNamedVar(c aClassCInstance);
my bad.
Provide a public accessor method that gives access to the variable, and make sure you don’t hide its name in class b and class c.
Then take a reference to an
ain oyur function:Then you can call it with
borcinstances:Bear in mind that in your code, the variable
varis private, as well as the inhericance in classesbandc. For this to work, you would need to make the inheritance public: