+2 votes
in C Plus Plus by
When would you use Categories over Inheritance and vice versa?

1 Answer

0 votes
by
  • If you are adding functions, but not data, use a category. An example of this is adding functions to NSMutableData which allow you to remove X bytes from a section of the data, or remove all BUT X bytes from the data. It doesn't make sense to create an entire sub-class simply to add these two functions, nor does it makes sense to write functions that aren't attached to a class (a plain C function). This allows you to attach the functionality to the class without creating a new, uneeded relationship, and doesn't change any part of existing functionality.

  • If you need to add/change data and add functionality to manipulate that data, or change functionality to represent a sub-type of object in your controller model, then you sub-class. For example, NSMutableData is a sub-class because it still uses NSData accessors, however, it changes the data representation internally so it can also manipulate the data. In this case a sub-class makes sense because it is no longer NSData, it is a /mutable/ NSData object (new keyword added to describe the object).

Related questions

+2 votes
asked Jan 19, 2022 in C Plus Plus by DavidAnderson
+1 vote
asked Apr 11, 2020 in SAP by amita rallin
...