Structure and class hierarchy (making template)

I have structures Aa, Bb, Cc, which inherit one common structure ABC and classes A, B, C, which inherit structures Aa, Bb, Cc. Each of them contains virtual methods. There is a common part and “unique” part in classes A, B, C. Here is a code:

#include <iostream>
using namespace std;

struct ABC {
    virtual ~ABC() {
    };
    virtual void printABC() = 0;
    virtual void someMethod() = 0;
};

struct Aa: ABC {
    virtual void printA() = 0;
};

struct Bb: ABC {
    virtual void printB()=0;
};

struct Cc: ABC {
    virtual void printC()=0;
};

class A: public Aa {
public:
    A() {
    }
    virtual ~A() {
    }
    //unique part
    void printA() {
        cout<<"A!"<<endl;
    }
    //common part
    void printABC() {
        cout<<"ABC"<<endl;
    }
    void someMethod() {
        cout<<"ABC!"<<endl;
    }
};

class B: public Bb {
    public:
    B() {
    }
    virtual ~B() {
    }
    //unique part
    void printB(){
        cout<<"B!"<<endl;
    }
    //common part
    void printABC() {
        cout<<"ABC"<<endl;
    }
    void someMethod() {
        cout<<"ABC!"<<endl;
    }
};

class C: public Cc {
    public:
    C() {
    }
    virtual ~C() {
    }
    //unique part
    void printC(){
        cout<<"C!"<<endl;
    }
    //common part
    void printABC() {
        cout<<"ABC"<<endl;
    }
    void someMethod() {
        cout<<"ABC!"<<endl;
    }
};

It seems to be not optimal. Is it possible to make template for A, B, C and how? Or, maybe, it’s better to make new class with all common methods within or make hierarchy. Suppose, we cannot change structures: ABC, Aa, Bb, Cc, but we can change classes A, B, C. Which method is more elegant and how to realize it better?


Source: oop

Leave a Reply