I have two classes that has some common functions and some different functions.
Let's say
class Red{
public:
void funcA();
void funcC();
}
class Blue{
public:
void funcB();
void funcC();
}
Note My actual code contains more functions (both common function and non-common one)
and I need to make a class for an interface that
- initialize one of the two classes above.
- contains the function to run each function in the class above if it is available for that class
Here is the example
interface.cpp
Red *red_object = nullptr;
Blue *blue_object = nullptr;
void init(int mode){
if (mode == 0) red_object = new Red();
else blue_object = new Blue();
}
void run_func_a(){
if (mode == 0) red_object->funcA();
}
void run_func_b(){
if (mode == 1) blue_object->funcB();
}
void run_func_c(){
if (mode == 0) {
red_object->funcC();
}
else {
blue_object->funcC();
}
}
The problem is, I think it is very clunky (e.g., run_func_c()
) when I have to write it for every function so I want to somehow generalize it, like using inheritance. However, I cannot use it since there is some function that does not exist in both classes. I could fill in an empty function to the one that does not have it but it is not good in the long term.
Is there a better way to construct the interface file in a more precise and cleaner way?
Edit:
I would like to clarify what I imagine in case of inheritance as @AdrianMole mentioned.
I will have a base class Colour
.
class Colour{
void funcC();
}
class Red: public Colour{
void funcA();
}
But when I want to write the function in interface.cpp,
Colour colour_object = nullptr;
void init(int mode){
if(mode ==0) colour_object = new Red();
else(mode == 0) colour_object = new Blue();
}
void run_func_a(){
colour_object->funcA(); // This will have error
}
void run_func_c(){
colour_object->funcC(); // This is okay and looks clean.
}
colour_object->funcA()
will raise an error since it doesn't exist on the base class.
I can just add funcA() in base class, but imagine if I have like 10 common functions, 10 functions unique to Red
and 10 functions unique to Blue
. I think that will be a lot of function in base class. (Although if it is the best approach, I might set on this approach)
CodePudding user response:
Use virtual keyword to archive this.
Example:
class Color
{
public:
void funcColor()
{
cout<<"Color::funcColor()\n";
}
virtual void funcC()
{
cout<<"Color::funcC()\n";
}
};
class Red : public Color{
public:
void funcA()
{
cout<<"Red::funcA()\n";
}
void funcC()
{
cout<<"Red::funcC()\n";
}
};
class Blue : public Color{
public:
void funcB()
{
cout<<"Blue::funcB()\n";
}
void funcC()
{
cout<<"Blue::funcC()\n";
}
};
int main()
{
Color *color;
Blue blue;
Red red;
color=&blue;
color->funcC();
color=&red;
color->funcC();
return 0;
}