Is it possible to add some functionality to a class without subclassing? - c++

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.

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.)

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.

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.

Related

What is friend ostream

I'm a bit confused about what exactly this line of code means in my header file.
friend ostream & operator << (ostream &, const something &);
Can someone clarify for me?
That line of code says that the operator << is a friend of something (since it's listed in the something class definition). This means that that operator << function can access the variables inside there.
The & here as the parameters mean that you pass in objects when calling the method and those parameters will just be another name for those parameter objects. Returning ostream & means that you're going to return the ostream parameter so that you can connect << expressions together avoiding creating a new "cout" when using the one global cout is what is needed.
As mentioned in many places, friend is a bypass to the normal protection mechanisms of C++ - it allows the function in question to access protected/private members, which normally only class members can do.
You'll often seen operators declared friends, because operators are never inside the class itself, but often need to modify something in the class and/or access private information. I.E. you may not want an external function to be able to muck with your internal pointers etc, but you may want to be able to print them out for status etc. You don't see them used very often otherwise - technically, it breaks encapsulation - but operators are kind of a special case.
A C++ class may declare another class or a function to be a friend. Friendly classes and methods may access private members of the class. So, the free operator method <<, not defined in any class, may insert somethings into a stream and look at and use the private members of something to do its work. Suppose something were complex:
class complex {
private:
double re;
double im;
public:
complex(double real = 0.0, double imag = 0.0) : re(real), im(imag) {}
friend ostream & operator<<(ostream& os, complex& c);
};
ostream & operator<<(ostream& os, complex& c){
os << c.re << std::showpos << c.im;
return os;
}
The friend keyword can name either functions or entire classes. In either case, it means that the implementation of the named function, or the named class, is allowed to access private and protected members of the class in which the friend declaration appears.
In this case, it means that this particular overload of the operator<< function is allowed to access internals of the something class, in order to write then to an output stream such as std::cout.

Which C++ operators can not be overloaded without friend function?

Which C++ operators can not be overloaded at all without friend function?
You only need a friend declaration if:
You define the operator as a standalone function outside the class, and
The implementation needs to use private functions or variables.
Otherwise, you can implement any operator without a friend declaration. To make this a little bit more concrete... one can define various operators both inside and outside of a class*:
// Implementing operator+ inside a class:
class T {
public:
// ...
T operator+(const T& other) const { return add(other); }
// ...
};
// Implementing operator+ outside a class:
class T {
// ...
};
T operator+(const T& a, const T& b) { return a.add(b); }
If, in the example above, the "add" function were private, then there would need to be a friend declaration in the latter example in order for operator+ to use it. However, if "add" is public, then there is no need to use "friend" in that example. Friend is only used when granting access is needed.
*There are cases where an operator cannot be defined inside a class (e.g. if you don't have control over the code of that class, but would still like to provide a definition where that type is on the left-hand side, anyway). In those cases, the same statement regarding friend declarations still holds true: a friend declaration is only needed for access purposes. As long as the implementation of the operator function relies only on public functions and variables, a friend declaration is not needed.
The operators where the left-hand-side operand is not the class itself. For example cout << somtething can be achieved via defining a std::ostream& operator<<(std::ostream& lhs, Something const & rhs); function, and marking them as friend inside the class.
EDIT: Friending is not needed, ever. But it can make things simpler.
The only reason to use friend function is to access the private(including protected) member variable and functions.
You never need a friend function. If you don't want the operator to
be a member (usually the case for binary operators which do not modify
their operands), there's no requirement for it to be a friend. There
are two reasons one might make it a friend, however:
in order to access private data members, and
in order to define it in the class body (even though it is not a
member), so that ADL will find it
The second reason mainly applies to templates, but it's common to define
operators like + and - in a template base class, in terms of +=
and -=, so this is the most common case.
Operator overloading and friendship are orthogonal concepts. You need to declare a function (any function) friend whenever it needs access to a private member of the type, so if you overload an operator as a function that is not a member and that implementation needs access to the private members, then it should be friend.
Note that in general it is better not to declare friends, as that is the highest coupling relationship in the language, so whenever possible you should implement even free function overloads of operators in terms of the public interface of your type (allowing you to change the implementation of the type without having to rewrite the operators). In some cases the recommendation would be to implement operatorX as a free function in terms of operatorX= implemented as a public member function (more on operator overloading here)
There is an specific corner case, with class templates, where you might want to declare a free function operator as a friend of the template just to be able to define it inside the template class, even if it does not need access to private members:
template <typename T>
class X {
int m_data;
public:
int get_value() const { return m_data; }
friend std::ostream& operator<<( std::ostream& o, X const & x ) {
return o << x.get_value();
}
};
This has the advantage that you define a single non-templated function as a friend in a simple straightforward way. To move the definition outside of the class template, you would have to make it a template and the syntax becomes more cumbersome.
You need to use a friend function when this is not the left-hand-side, or alternatively, where this needs to be implicitly converted.
Edit: And, of course, if you actually need the friend part as well as the free function part.
operators [] -> =
Must be a member functions.
Other binary operators acceptable for overloading can be write in function form or in memeber-function form.
Operators acceptable for overloading is all unary and binary C++ operators except
: . :: sizeof typeid ?

Consistency in placing operator functions

I have a class like this:
class A {
...private functions, variables, etc...
public:
...some public functions and variables...
A operator * (double);
A operator / (double);
A operator * (A);
...and lots of other operators
}
However, I want to also be able to do stuff like 2 * A instead of only being allowed to do A * 2, and so I would need functions like these outside of the class:
A operator * (double, A);
A operator / (double, A);
...etc...
Should I put all these operators outside of the class for consistency, or should I keep half inside and half outside?
IMHO, the concern shouldn't be with stylistic consistency, but with encapsulation consistency; generally if a function does not need access to private members, it should not be part of the class. This is not a hard an fast rule, see arguments for it here.
So if your operators do not require private access, put them all outside. Otherwise, they will all have to be inside like so:
class A {
...
public:
...
A operator * (double);
A operator / (double);
friend A operator * (double, A);
friend A operator / (double, A);
...
};
From your replies to comments in the question it seems that you have an implicit conversion from double to A in your class. something like:
class A
{
// ...
public:
A(double);
// ...
};
In this case you can simply define a free function for each operator of the form:
A operator*( const A&, const A& );
and it will be used if either side is an A object and the other side is implicitly convertible to an A. For this reason it is often preferable to make symmetric binary operators free functions.
Frequently it can be easier to implement binary * in terms of the assignment version *=. In this case I would make the assignment version a member function and define * as something like:
A operator*( const A& l, const A& r )
{
A result(l);
result += r;
return result;
}
Otherwise as operator* is plainly part of your class interface I would have no problem with making it a friend if required.
So what you are saying is that because you must put some operators (the ones that don't have A as the first param) outside the class, maybe you should put them all there so people know where to find them? I don't think so. I expect to find operators inside the class if at all possible. Certainly put the "outside" ones in the same file, that will help. And if the outside ones need access to private member variables, then adding the friend lines is a huge hint to look elsewhere in the file for those operators.
Would I go so far as to include the friend lines even if my implementation of the operators could actually be done with public getters and setters? I think I would. I think of those operators as really being part of the class. It's just that the language syntax requires them to be free functions. So generally I use friend and I write them as though they were member functions, not using getters and setters. It's a pleasant side effect that the resulting need for friend statements will cause them all to be listed in the definition of the class.

c++ overloaded method in derived class

I have the following question:
Assume base class A with method:
A& operator+(A& a) {...}
I also have a derived class B which overloads (or at least it should so) this method:
A& operator+(B& b) {...}
The problem is that if i want to call something like:
b + a (where b is of type B and a of type A) i get a compile error.
(error C2679: binary '+' : no operator found which takes a right-hand operand of type 'A' (or there is no acceptable conversion)).
Shouldnt that call the base class method? (it looks like it overrides the method..)
If not, why? Is there a way to fix this (dont tell me to overload the method in B with A&)
Sorry i dont give examples in formated text, but i dont know how to format it.
Thanks in advance!
PS Im using Visual studio 2010 beta.
No, it won't call the base class function. Class B has an operator+, it doesn't take the correct parameter, end of story.
You can define operator+ as a free function, not in any class. Perhaps a friend, if it needs to access private data:
A operator+(const A &lhs, const A &rhs) { ... }
B operator+(const B &lhs, const B &rhs) { ... }
Then b + a will call the first operator, as will a + b. b + b will call the second.
Alternatively, you could "un-hide" the base class implementation, by putting this in class B:
using A::operator+;
it's probably best not to, though. Most operators work better as free functions, because then you get automatic conversions on both operands. C++ never performs conversions on the LHS of a member function call.
Btw, operator+ almost certainly should return by value, not by reference, since an automatic (stack) variable no longer exists once the function returns. So the caller needs to be passed a copy of the result, not a reference to it. For this reason operator+ and inheritance aren't a great mix, although it can probably work as long as the caller knows what they're doing.
The problem is called hiding - a member function in a derived class hides functions with the same name in the base class. In this case you can't access A::operator+(A&) because it's being hidden by B::operator+. The way to fix this is to define B::operator+(A&), and possibly have it call the base class function.
Edit: There's a section in the C++ FAQ Lite that goes into more detail about this problem and offers another possible solution, namely the using keyword.
The problem is that you are defining the member operator, so when called as b + a it results in b.operator+( a ), which doesn't exist.
Accepted practice is to define free operators that themselves would call [virtual] members on the arguments.
Edit:Standard example of what I'm talking about is adapting a class hierarchy for output streaming:
class base
{
public:
virtual ~base();
virtual void print( std::ostream& ) const;
};
std::ostream& operator<<( std::ostream& out, const base& b )
{
b.print( out ); return out;
}
This doesn't really work for math operations since you want to return by [const] value, not reference, i.e. avoid nonsense like a + b = c;.
For example, addition of real and complex numbers is defined, but yields complex number as the result, so you cannot derive complex from real. The other way - maybe. But still you want to define exact operations interface:
const real operator+( const real&, const real& );
const complex operator+( const complex&, const complex& );
Hope this gives you enough to re-think your design :)
Couple of things come to mind. First, you would generally want to make the operator + "virtual". Then, the derived operator + taking a reference to B would be an override due to co-variance, instead of hiding the base class implementation, which is what is happening here.
That said, I suspect (but can't say for certain without compiling a test project) that that would actually solve your problem. That's because the standard answer for binary operators is to use static methods that take two parameters on the class. The C++ STL uses this technique extensively, and I don't know of a reason to attempt to implement binary operators as instance methods, virtual or not. It's just too confusing, with no real up-side.

C++ Templates vs. Aggregation

Consider the following piece of code:
class B {
private:
// some data members
public:
friend bool operator==(const B&,const B&);
friend ostream& operator<<(ostream&,const B&);
// some other methods
};
template <typename T=B>
class A {
private:
// some data members
vector<vector<T> > vvlist;
public:
// some other methods
};
My requirement is that the type T that is passed as type parameter must provide definitions for the operator== and the operator<< methods. I do not want to enforce any other restrictions on T.
How can I do this?
One way that I can think of is to Create an Abstract class say "Z" that declares these two methods.
and then write
vector<vector<Z> > vvlist;
and NOT have class A as a template.
Is there a better way to do this?
It happens automatically.
If your code calls the operators == and <<, then the code simply won't compile if the class is passed a type that doesn't define these operators.
It is essentially duck-typing. If it looks like a duck, and quacks like a duck, then it is a duck. It doesn't matter whether it implements an IDuck interface, as long as it exposes the functionality you try to use.
It seems like you are looking for a concept check library. See what Boost has to offer: Boost Concept Check Library. That link also has a good explanation what concepts are. Quote:
A concept is a set of requirements
(valid expressions, associated types,
semantic invariants, complexity
guarantees, etc.) that a type must
fulfill to be correctly used as
arguments in a call to a generic
algorithm
In your question, the concept is "type T must provide operator== and operator<<".
You can write a private method in A that would test required stuff on T in compile time.
void TestReq(T x, T y)
{
if (x==y)
cout << x;
}
This way even plain integers would pass and work.