Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inheritance pattern

I am after your opinion on how best to implement an inheritance pattern in C++. I have two base classes, say

class fooBase{
protected:
    barBase* b;
};

class barBase{};

where fooBase has a barBase. I intend to put these classes in a library, so that wherever I have a fooBase it can use its barBase member.

I now intend to create a specialisation of these in a specific program

class fooSpec : public fooBase{};
class barSpec : public barBase{};

Now I want fooSpec::b to point to a barSpec instead of a barBase. I know that I can just initialise b with a new barSpec, but this would require me to cast the pointer to a barSpec whenever I wanted to use specific functions in the specialisation wouldn't it?

Is there another way that this is often acheived?

Cheers.

like image 333
DrBards Avatar asked Apr 16 '26 09:04

DrBards


1 Answers

Create a method in your specclass to cast the b into the special version. That way instead of casting it all the time, it looks like a getter.

On the other hand OO is about programming towards interfaces and not objects. So what you are doing here looks like programming towards objects. But the is difficult to see as this example is purely theoretical.

like image 107
Philip Stuyck Avatar answered Apr 17 '26 22:04

Philip Stuyck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!