Dontumindme
Dontumindme

Reputation: 21

Is there some way not to repeat the code in inherited classes

I have an abstract class A and 2 classes that inherits from class A wchich are B and C. Let's leave class B and take a closer look to class C. I have couple of classes that inherits from class C wchich are C1, C2 and so on...

class A{
protected:
char symbol;
public:
virtual char get_symbol() = 0;
};

class C : public A{
public:
virtual char get_symbol() { return symbol;}
};

class C1 : public C{
protected:
char symbol = '#';
};

The problem is that when i want to call a get_symbol() method for C1,C2... objects i am getting a method from C and some random chars. I have to write:

char get_symbol() { return symbol;}

for all of the Cn classes to get their actual symbol.

My question is: is there any solution to avoid code redundance and get the proper symbol of Cn objects(the C type object doesn't even have his symbol)

Regards

Upvotes: 2

Views: 80

Answers (1)

davidhigh
davidhigh

Reputation: 15528

CRTP aka static inheritance can help here:

struct A{
    virtual char get_symbol() const = 0;
};

template<typename Derived>
struct C : public A{
    virtual char get_symbol() const override {
         return static_cast<Derived const&>(*this).symbol;
    }
};

struct C1 : public C<C1>{
    char symbol = '#';
};

Upvotes: 2

Related Questions