Elliot MacNeille
Elliot MacNeille

Reputation: 91

Encapsulation vs Inheritence

My language is c++ but I feel the answer should be general

I can choose between two option for my class, B:

1) Have B inherit from A, and make some of the methods of A virtual

2) Declare an instance of A within B.

This question is about what is optimal in terms of run time, as both will work fine.

What I think is option 1 is less optimal for instances of both A and B because there is a layer of indirection at run time as the correct function is choosen from the V table.

Is this correct?

Upvotes: 1

Views: 190

Answers (1)

mbmcavoy
mbmcavoy

Reputation: 2686

Unless your code is performance-critical, you should not worry about the difference in run-time indirection. You should use the option that makes sense within the context of your application.

For Option 1, B is an A.

For Option 2, B has an A.

If the code is performance-critical, you should implement and test both versions, as mentioned by Almo.

Upvotes: 3

Related Questions