tags:

views:

107

answers:

3

Hi,

In Ojective-C there is something called Categories which allow the user to add methods from outside the original .h or .m file (objective-c's version of .cpp) I wonder if there exist such functionally in C++.?

I specially want implement << operator for debugging and maybe others of a class that is in a library I frequently use. (And don't want to use macros since it looks ugly ;) )

Thanks.

+5  A: 

You could always overload operators outside of the class.

std::ostream& operator<< (std::ostream& f, const YourClass& cls) {
  ...
}

You still need to friend this function if it needs to access private members of YourClass.

(But it's not possible to define normal member functions like what Objective-C does.)

KennyTM
Just to add Extraction(>>) and Insertion(<<) operators cannot be overloaded through member functions. Must be overloaded through Friend functions.
Als
+1 for the clarification: "not possible to define normal member functions"
nacho4d
@Als: The `>>` and `<<` operators can't be overloaded through member functions only because our custom class is on the right-hand side.
KennyTM
@Als: you're wrong, serialization class and logging classes usually have a few of them as members.
Matthieu M.
@KennyTM: The custom class is always going to end up on the right side of << or >> won't it? Any example wherein the other way round?
Als
@Als: Like, when you subclass the stream.
KennyTM
+4  A: 

Yes, it's possible to add an overload for operator << outside of the class:

ostream& operator <<(ostream& lhs, const SomeClass& rhs) {
    /* Output something to lhs using rhs object */
    return lhs;
}

The only problem with this is that the function won't have access to SomeClass' private/protected members; to do that you must declare this function a friend inside the class. But if you get all the required information through the public interface, then it's not an issue.

reko_t
+3  A: 

Yes, the Namespace principle is almost similar to this. The idea is to have closely related class operations outside the class in the same namespace as the class. Operator overloading as @KennyTM suggested is a fallout of this principle (the way I look at it)

Also look at the visitor design pattern

Intent

Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Chubsdad
+1 because of the link... I read them, I don't plan to use that now, but it is good to know
nacho4d
@nacho4d: great. Just want to let you know that if you are using @KennyTM's solution correctly, you are unknowingly using the Namespace Principle. Have fun!
Chubsdad