views:

208

answers:

4

Is there a way to implement functionality like Class Categories (of Objective-C) or Extension Methods (of C# 3.0) in C and/or C++?

+1  A: 

With regard to C#'s extension methods: Not directly. C++ has less need for these things because C++ supports free functions. I've never used Objective-C so I can't comment there.

Billy ONeal
A: 

C++ doesn't have sealed classes or single class inheritance, so in most cases you can subclass the base class. There are creative ways to make a class non-inheritable, but they are few and far in between. In general, C++ doesn't have the problems C# does that gave birth to extension methods.

C is not Object Orientated, so the question doesn't really apply.

Igor Zevaka
What "problems in C#" gave birth to extension methods? Extension methods exist solely to support LINQ, a feature C++ does not have in any description.
Billy ONeal
Sealed classes and single class inheritable. Apart from LINQ Extension methods provide an ability to extend class's functionality, which is not possible when class is sealed (like `string`). Similarly the restriction on inheriting one class limits your ability to add mixins.
Igor Zevaka
@Igor Zevaka: Yes, but classes in C++ are effectively sealed when they don't have virtual destructors, so I don't see how C++ doesn't have the same problem.
Billy ONeal
A: 

Can you use an interface? Extension methods are an easy way to avoid subclassing, but they are rendered semi-useless when proper OO techniques are used. The reason that they are used with Linq so much is so that the VS team did not have to go and update code that would most likely break a lot of legacy applications.

Per MSDN: "In general, we recommend that you implement extension methods sparingly and only when you have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type."

http://msdn.microsoft.com/en-us/library/bb383977.aspx

Nate Noonen
Although having a LinqList would make me smile.
Nate Noonen
+1  A: 

Not really. It's not the C++ way to treat classes like this.

Amongst others, Meyers argue that it's best to have a small class with the minimal set of operations that make it fully useful. If you want to expand the feature set, you may add an utility namespace (e.g. namespace ClassUtil) that contains non-member utility functions that operate on that minimal class. It's easy to add functions to a namespace from anywhere.

You can check a discussion on the subject here.

kotlinski
Free functions ARE the way to go.
Matthieu M.