简体   繁体   中英

Inheritance and member functions

Consider I have series of derived classes for example as listed below:

class A
{
...
}

class B1 : public A //there may be many B's here say, B2, B3 etc
{
 ...
}
class C1 : public B1 //may be more C's as well
{
...
}

I would like to put all of the objects in single container, thus all would be of type class A .

Suppose I would like to add a function to class C1 , what would be the best way to achieve this? My options would be introducing it in the base class A and write the needed implementation in C1 , or, I could introduce it in C1 and do dynamic casting to access it. Which one is preferred? Is dynamic casting too expensive? (My main constrain is the run time.I have a flag in the base class to indicate what type of derived object it is, thus I do not have to dynamic cast every object in the container. Does adding unnecessary functions to base class can result in bad instruction cache use?)

You don't tell us the purpose of the new function in C1 , and this does affect the answer, but as rough guidelines:

  • If the new function is a general behavior that you may need on any object and C1 happens to be the first user, definitely just add the interface to A .
  • If the new function is specific to the C series of classes but it can follow some general pattern (for example post-processing), add a post_process method to A , override it in C1 , and have that method call private implementation methods of C1 to do the actual specific post-processing task.
  • If neither of these are the case you may wish to reconsider your use of inheritance as it's possible you're using it to represent a relationship other than substitution.

adding a virtual function to your base class A is better because:

  • you should avoid dynamic cast especially in performance sensitive code. Please see Performance of dynamic_cast?

  • you should avoid having conditions to examine the object type (eg is it A, B1, or C1 ?) before performing a type-specific operation. Not only because it's slow, but also because if you do so, every time you add a new object type (eg C2) you will need to check all those conditions to see if they need to be updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM