-
Organizing Inheritance
Here's a bit of pseudocode describing the situation I'm in...
Code:
class Base{
public:
void method(){
//do some stuff
protectedFunc(foo);
//do some stuff with foo
};
protected:
void protectedFunc(Foo* foo){
//do some stuff
};
}
class Inherited : public Base{
public:
void method(){
//do same stuff as Base
protectedFunc(foo);
//do same stuff with foo
}
protected:
void protectedFunc(Foo* foo){
//do some DIFFERENT stuff
};
}
Obviously, I could copy and paste the code like I have listed here. Alternatively, I could divide the function into methodPartA(), protectedFunc(), and methodPartB(). This just seems a bit ungainly in terms of appearance. Is there a better way that I'm missing?
-
So if I understand you correctly you want method() to do the same thing in both classes and protectedFunc() to behave differently depending on if it's a base or inherited object?
Then you could leave out the declaration of method() in Inherited, and declare protectedFunc() as virtual in Base
-
Your design could be correct, except that you should not redefine method in the derived class. You just need to override protectedFunc, which can be declared as a private virtual function in the base class. This is known as the non-virtual interface idiom.
-
Thanks. the NVI idiom was what I was looking for. It's been a long day...