Function outside of class in C++ [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Operator overloading outside class
I'm not great with C++ but I've been tasked with creating a custom Vector class that uses a lot of operator overloads. I'm having a hard time grasping how to do one of them.
The class should provide functions for the following:
v3 = v2 * 2.0f;
v3 = 2.0f * v2;
I successfully implemented the first one by overloading the * operator. I'm not sure how to go about the second one though. I know I need to overload the * operator again, but I don't think it should be inside of my vector class. I was absent from class the day my professor explained it, and when I talked to him afterwards he mentioned that it needs to be outside of the class. The problem is that I have no idea how that will work. Any guidance would be great!
EDIT-
#Fede_Reghe That makes sense to me, but when I added it I am now getting this error from the compiler:
Vector.h:64: error: passing ‘const Vector’ as ‘this’ argument of ‘float Vector::operator’ discards qualifiers
In the header, I have these two lines that refer to the * overloads.
Vector operator * (float);
friend Vector operator*(float, const Vector&);
Then I overloaded the [] so that it returns a float of the x, y, or z value. That looks like this in the header:
float operator [] (int);
Outside of the class, I defined the friend * overload like this:
Vector operator * (float f,const Vector& v2)
{
float newX = v2[0] * f;
float newY = v2[1] * f;
float newZ = v2[2] * f;
Vector newVector(newX, newY, newZ);
return newVector;
}
I don't fully understand what the error message means.

You should overload operator outside class and declare it as friend of the class.
For example:
class Vector {
// ...
friend Vector operator*(float, Vector);
};
Vector operator*(float num1, Vector num2)
{
// ...
}

You need the two-argument implementation of operator *(). Here is an example of doing so with operator +() that you can generalize.

Related

Overloading an operator to allow different order of parameters in C++

Let's say I'm writing a class to represent 3D vectors for a computer graphics application. I would like to be able to multiply vectors by scalars, as shown below:
Vector3D vec(1, 2, 3); // The paramaters of the constructor are the x, y and z values
Vector3D vec1 = vec * 2; // Case A: result should be (2, 4, 6)
Vector3D vec2 = 2 * vec; // Case B: result should be (2, 4, 6)
To make case A work, I could add the following function to my class:
class Vector3D
{
public:
// ...
const Vector operator*(int scalar) const;
};
To make case B work, I would have to create a function outside of my class:
const Vector operator*(int scalar, const Vector& vec);
Note that I could also make case A work by adding the following function outside of my class:
const Vector operator*(const Vector& vec, int scalar);
My question is: what is the cleanest way to do this? I could add one function inside my class and one function outside of it, or I could add two functions outside of my class. I like the idea of adding two functions outside of the class because I could keep them next to each other, which I think is clearer since they essentially do the same thing, but does adding one of the functions inside the class have any benefits that I am not seeing?
Note that the return values of my functions are const so that users can't do this (as explained by Scott Meyers in his book Effective C++):
Vector3D vecA(1, 2, 3);
Vector3D vecB(1, 2, 3);
Vector3D vecC(1, 2, 3);
vecA * vecB = vecC;
The usual approach is to provide operator *=(int) as a member function and then write free functions operator*(Vector3D, int) and operator*(int, Vector3D) that call it.
Since multiplying a vector by scalar is symmetric, in the sense that there's no clear "superior" or "subordinate" participant, I would use a pair of free-standing operator overloads:
const Vector operator*(int scalar, const Vector& vec);
const Vector operator*(const Vector& vec, int scalar);
When you have a choice between overloading a member function vs. overloading a freestanding function, the decision should be based on the participation of the object itself in the computation with respect to function's parameters.
When the object plays central role, while parameters play peripheral role, keep the function with the object by making it a member. When the object and function parameters play similar roles, i.e. when there is a degree of symmetry between participants, a freestanding function is more appropriate.
The operator* here is symmetric (as in a * b and b * a should be equivalent operations) so you should prefer having both of the functions outside of the class.
Aside from what you mentioned - that having them near each other makes it cleaner - it also allows implicit conversions for either operand. On the other hand, if you had the operator* for Case A be a member function then implicit conversions of the left hand operand to Vector3D type is not allowed, but conversions of the right hand operand to Vector3D type is allowed (unless you mark the constructors explicit, but that's besides the point).
By using twin nonmember functions we have true symmetry, in that both operands have the same ability to be converted to the Vector3D type.
By the way, the C++ Core Guidelines written by Bjarne Stroustrup and Herb Sutter also suggest doing this.

Multiplication operator overloading

I am implementing a class Vector and defined the multiplication operator as a member of the class as
Vector operator*(const float& s);
as far as I understand, this means that the left operand is a Vector and the right operand is a float. So if I try and do something like this
Vector c(1,2,3);
Vector d = c * 2.0f; // Results in d = (2,4,6)
that's ok, however, to my eyes is weird to see first the vector then the scaling factor, so in order to have float * Vector I defined a non-member function as
Vector operator*(const float& s, const Vector& v)
{
//Invalid operands to binary expression 'const Vector' and 'float'
return v * s;
}
However I received the error in the comment. I don't know what am I missing or if this is not the way I should declare the operator in order to do the scaling in float * Vector fashion.
Notice that you're passing v as const Vector &, but your member operator* is not marked as const. So it can only be called on non-const Vector objects. This is most certainly not what you want, so just mark the member as const:
Vector operator*(const float& s) const;

C++ operator overload with friend

I'm trying to achieve this using parameter overloading using C++:
Complex c(3.0, 4.0);
double magnitude = | c; // magnitude will be 5
I wrote the following code: (Only the necessary part here..)
class Complex
{
public:
double _real;
double _imaginary;
friend double operator|(const Complex &c1)
{
return sqrt(c1._real * c1._real + c1._imaginary * c1._imaginary);
}
}
But I get the following error:
error C2805: binary 'operator |' has too few parameters
Is that impossible to use operator | with only 1 parameter?
friend double operator|(const Complex &c1)
{
return sqrt(c1._real * c1._real + c1._imaginary * c1._imaginary);
}
This doesn't define a member operator, just FYI.
double magnitude = | c;
this is invalid syntax, | is a binary operator.
Correct way:
class Complex
{
public:
double _real;
double _imaginary;
double getMagnitude() const // POP POP!
{
return sqrt(_real * _real + _imaginary * _imaginary);
}
}
No more bonus.
Is that impossible to use operator | with only 1 parameter?
You can overload operators as long as atleast one of the types involved is an user defined type but you cannot change the behavior w.r.t how many parameters they can take.
As the error message tells you | is a binary operator you cannot overload it to act as an unary operator.
What is the correct way to do this?
You should provide a utility function for your class Complex, do name it appropriately and it will to do the job for you in the best possible way.
Note that the very basic rule of operator overloading is:
"Whenever the meaning of an operator is not obviously clear and undisputed, it should not be overloaded. Instead, provide a function with a well-chosen name."
The rule is meant for non-intuitive operator usage like this.
operator| is a binary operator. As binary operator, it needs 2 parameters. If you want to do what you want to do here, you must use an unary operator.
Anyway - it looks like a bad idea since it is not obvious from looking at the operator to see what it does.
No - the '|' operator is a binary operator, meaning that it takes two parameters. You can overload operators but not change their "arity". Some operators are available with multiple arities though.
Unary operators include:
+
-
++ (both pre and post versions)
-- (both pre and post versions)
!
~
*
&
(cast) (but you would have to define a suitable casting type to get your double result)
The best solution from a software engineering point of view would probably be an explicit method to get the modulus - e.g. getModulus(). But you could legitimately argue that a double cast is OK.
For the latter case, you would have:
class Complex
{
public:
double _real;
double _imaginary;
operator double() const
{
return sqrt(this._real * this._real + this._imaginary * this._imaginary);
}
}
and use it as follows:
Complex c(3.0, 4.0);
double magnitude = c; // magnitude will be 5
Is that impossible to use operator | with only 1 parameter?
Yes. operator| is a binary operator. That means it takes two arguments. What you're looking for is operator|=
struct wtf
{
double operator|= (double omg)
{
return 42.;
}
};
int main(){ wtf omg; omg|= 42.; }

Const correctness and operator *

I defined a class like this:
Quaternion& conjugate(); //negates the vector component of the quaternion
Quaternion conjugate() const; //same but in without modifying the class...
Quaternion& operator = (Quaternion const& Qrhs);
Quaternion& operator *= (Quaternion const& Q);
Quaternion operator * (Quaternion const& Qrhs) const;
now I use this functions like this:
PRINTVAR(*this); //this is the first time printed (a little macro to print line and file)
Quaternion vQ(0.,vn), resQ;
resQ = vQ*(this->conjugate()); //this is the method I want to discuss...
PRINTVAR(*this); //this is the second time
resQ = *this * resQ;
and this is the output
*this: (0:0:0:0) at line: 128 in file: Quaternions.cpp
*this: (-0:-0:-0:0) at line: 131 in file: Quaternions.cpp
I thought that by calling the operator * in the line resQ = vQ*(this should be called as const)...
why if I print *this again is changed?
here is the definition of the conjugate function:
Quaternion& Quaternion::conjugate(){
/* Given: Nothing
* Task: Invert sign of the vector
* Return: the class which will be modified
*/
V3 vec;
vec = -(this->getVector());
x() = vec[0];
y() = vec[1];
z() = vec[2];
return *this;
}
Quaternion Quaternion::conjugate() const{
Quaternion result(*this);
result.conjugate();
return result;
}
If the code you showed is in a non-const method, than the this pointer is non-const, and the non-const conjugate method is of course a better match than the const one. Return types aren't considered in overload decisions. If you want to insist that the const version is used, you can add constness: resQ = vQ*(static_cast<const Quaternion*>(this)->conjugate());
Probably the method in which you are using this is non-const.
The type of this a member function of a type A, is A * const. For const member function it is const A * const.
Therefore, your code will work as you expect it to do if you enter your code into const method.
If you want to force calling const overload of function you will need to do a const-cast:
const_cast<const Quaternion * const>(this)->conjugate();
*this is not const (although it is used in a const method), and the c++ FAQ Lite states regarding const overloading (in the FAQ's case on a subscript operator);
When you apply the subscript operator to a MyFredList object that is
non-const, the compiler will call the non-const subscript operator.
Translated, since *this is non-const, the non-const method will be called.

What is an overloaded operator in C++?

I realize this is a basic question but I have searched online, been to cplusplus.com, read through my book, and I can't seem to grasp the concept of overloaded operators. A specific example from cplusplus.com is:
// vectors: overloading operators example
#include <iostream>
using namespace std;
class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};
CVector::CVector (int a, int b) {
x = a;
y = b;
}
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);
}
int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
}
From http://www.cplusplus.com/doc/tutorial/classes2/ but reading through it I'm still not understanding them at all. I just need a basic example of the point of the overloaded operator (which I assume is the "CVector CVector::operator+ (CVector param)").
There's also this example from wikipedia:
Time operator+(const Time& lhs, const Time& rhs)
{
Time temp = lhs;
temp.seconds += rhs.seconds;
if (temp.seconds >= 60)
{
temp.seconds -= 60;
temp.minutes++;
}
temp.minutes += rhs.minutes;
if (temp.minutes >= 60)
{
temp.minutes -= 60;
temp.hours++;
}
temp.hours += rhs.hours;
return temp;
}
From "http://en.wikipedia.org/wiki/Operator_overloading"
The current assignment I'm working on I need to overload a ++ and a -- operator.
Thanks in advance for the information and sorry about the somewhat vague question, unfortunately I'm just not sure on it at all.
Operator overloading is the technique that C++ provides to let you define how the operators in the language can be applied to non-built in objects.
In you example for the Time class operator overload for the + operator:
Time operator+(const Time& lhs, const Time& rhs);
With that overload, you can now perform addition operations on Time objects in a 'natural' fashion:
Time t1 = some_time_initializer;
Time t2 = some_other_time_initializer;
Time t3 = t1 + t2; // calls operator+( t1, t2)
The overload for an operator is just a function with the special name "operator" followed by the symbol for the operator being overloaded. Most operators can be overloaded - ones that cannot are:
. .* :: and ?:
You can call the function directly by name, but usually don't (the point of operator overloading is to be able to use the operators normally).
The overloaded function that gets called is determined by normal overload resolution on the arguments to the operator - that's how the compiler knows to call the operator+() that uses the Time argument types from the example above.
One additional thing to be aware of when overloading the ++ and -- increment and decrement operators is that there are two versions of each - the prefix and the postfix forms. The postfix version of these operators takes an extra int parameter (which is passed 0 and has no purpose other than to differentiate between the two types of operator). The C++ standard has the following examples:
class X {
public:
X& operator++(); //prefix ++a
X operator++(int); //postfix a++
};
class Y { };
Y& operator++(Y&); //prefix ++b
Y operator++(Y&, int); //postfix b++
You should also be aware that the overloaded operators do not have to perform operations that are similar to the built in operators - being more or less normal functions they can do whatever you want. For example, the standard library's IO stream interface uses the shift operators for output and input to/from streams - which is really nothing like bit shifting. However, if you try to be too fancy with your operator overloads, you'll cause much confusion for people who try to follow your code (maybe even you when you look at your code later).
Use operator overloading with care.
An operator in C++ is just a function with a special name. So instead of saying Add(int,int) you say operator +(int,int).
Now as any other function, you can overload it to say work on other types. In your vector example, if you overload operator + to take CVector arguments (ie. operator +(CVector, CVector)), you can then say:
CVector a,b,res;
res=a+b;
Since ++ and -- are unary (they take only one argument), to overload them you'd do like:
type operator ++(type p)
{
type res;
res.value++;
return res;
}
Where type is any type that has a field called value. You get the idea.
What you found in those references are not bad examples of when you'd want operator overloading (giving meaning to vector addition, for example), but they're horrible code when it comes down to the details.
For example, this is much more realistic, showing delegating to the compound assignment operator and proper marking of a const member function:
class Vector2
{
double m_x, m_y;
public:
Vector2(double x, double y) : m_x(x), m_y(y) {}
// Vector2(const Vector2& other) = default;
// Vector2& operator=(const Vector2& other) = default;
Vector2& operator+=(const Vector2& addend) { m_x += addend.m_x; m_y += addend.m_y; return *this; }
Vector2 operator+(const Vector2& addend) const { Vector2 sum(*this); return sum += addend; }
};
From your comments above, you dont see the point of all this operator overloading?
Operator overloading is simply 'syntactic sugar' hiding a method call, and making code somehwhat clearer in many cases.
Consider a simple Integer class wrapping an int. You would write add and other arithmetic methods, possibly increment and decrement as well, requiring a method call such as my_int.add(5). now renaming the add method to operator+ allows my_int + 5, which is more intuitive and clearer, cleaner code. But all it is really doing is hiding a call to your operator+ (renamed add?) method.
Things do get a bit more complex though, as operator + for numbers is well understood by everyone above 2nd grade. But as in the string example above, operators should usually only be applied where they have an intuitive meaning. The Apples example is a good example of where NOT to overload operators.
But applied to say, a List class, something like myList + anObject, should be intuitively understood as 'add anObject to myList', hence the use of the + operator. And operator '-' as meaning 'Removal from the list'.
As I said above, the point of all this is to make code (hopefully) clearer, as in the List example, which would you rather code? (and which do you find easier to read?) myList.add( anObject ) or myList + onObject? But in the background, a method (your implementation of operator+, or add) is being called either way. You can almost think of the compiler rewritting the code: my_int + 5 would become my_int.operator+(5)
All the examples given, such as Time and Vector classes, all have intuitive definitions for the operators. Vector addition... again, easier to code (and read) v1 = v2 + v3 than v1 = v2.add(v3). This is where all the caution you are likely to read regarding not going overboard with operators in your classes, because for most they just wont make sense. But of course there is nothing stopping you putting an operator & into a class like Apple, just dont expect others to know what it does without seeing the code for it!
'Overloading' the operator simply means your are supplying the compiler with another definition for that operator, applied to instances of your class. Rather like overloading methods, same name... different parameters...
Hope this helps...
The "operator" in this case is the + symbol.
The idea here is that an operator does something. An overloaded operator does something different.
So, in this case, the '+' operator, normally used to add two numbers, is being "overloaded" to allow for adding vectors or time.
EDIT: Adding two integers is built-in to c++; the compiler automatically understands what you mean when you do
int x, y = 2, z = 2;
x = y + z;
Objects, on the other hand, can be anything, so using a '+' between two objects doesn't inherently make any sense. If you have something like
Apple apple1, apple2, apple3;
apple3 = apple1 + apple2;
What does it mean when you add two Apple objects together? Nothing, until you overload the '+' operator and tell the compiler what it is that you mean when you add two Apple objects together.
An overloaded operator is when you use an operator to work with types that C++ doesn't "natively" support for that operator.
For example, you can typically use the binary "+" operator to add numeric values (floats, ints, doubles, etc.). You can also add an integer type to a pointer - for instance:
char foo[] = "A few words";
char *p = &(foo[3]); // Points to "e"
char *q = foo + 3; // Also points to "e"
But that's it! You can't do any more natively with a binary "+" operator.
However, operator overloading lets you do things the designers of C++ didn't build into the language - like use the + operator to concatenate strings - for instance:
std::string a("A short"), b(" string.");
std::string c = a + b; // c is "A short string."
Once you wrap your head around that, the Wikipedia examples will make more sense.
A operator would be "+", "-" or "+=". These perform different methods on existing objects. This in fact comes down to a method call. Other than normal method calls these look much more natural to a human user. Writing "1 + 2" just looks more normal and is shorter than "add(1,2)". If you overload an operator, you change the method it executes.
In your first example, the "+" operator's method is overloaded, so that you can use it for vector-addition.
I would suggest that you copy the first example into an editor and play a little around with it. Once you understand what the code does, my suggestion would be to implement vector subtraction and multiplication.
Before starting out, there are many operators out there! Here is a list of all C++ operators: list.
With this being said, operator overloading in C++ is a way to make a certain operator behave in a particular way for an object.
For example, if you use the increment/decrement operators (++ and --) on an object, the compiler will not understand what needs to be incremented/decremented in the object because it is not a primitive type (int, char, float...). You must define the appropriate behavior for the compiler to understand what you mean. Operator overloading basically tells the compiler what must be accomplished when the increment/decrement operators are used with the object.
Also, you must pay attention to the fact that there is postfix incrementing/decrementing and prefix incrementing/decrementing which becomes very important with the notion of iterators and you should note that the syntax for overloading these two type of operators is different from each other. Here is how you can overload these operators: Overloading the increment and decrement operators
The accepted answer by Michael Burr is quite good in explaining the technique, but from the comments it seems that besides the 'how' you are interested in the 'why'. The main reasons to provide operator overloads for a given type are improving readability and providing a required interface.
If you have a type for which there is a single commonly understood meaning for an operator in the domain of your problem, then providing that as an operator overload makes code more readable:
std::complex<double> a(1,2), b(3,4), c( 5, 6 );
std::complex<double> d = a + b + c; // compare to d = a.add(b).add(c);
std::complex<double> e = (a + d) + (b + c); // e = a.add(d).add( b.add(c) );
If your type has a given property that will naturally be expressed with an operator, you can overload that particular operator for your type. Consider for example, that you want to compare your objects for equality. Providing operator== (and operator!=) can give you a simple readable way of doing so. This has the advantage of fulfilling a common interface that can be used with algorithms that depend on equality:
struct type {
type( int x ) : value(x) {}
int value;
};
bool operator==( type const & lhs, type const & rhs )
{ return lhs.value == rhs.value; }
bool operator!=( type const & lhs, type const & rhs )
{ return !lhs == rhs; }
std::vector<type> getObjects(); // creates and fills a vector
int main() {
std::vector<type> objects = getObjects();
type t( 5 );
std::find( objects.begin(), objects.end(), t );
}
Note that when the find algorithm is implemented, it depends on == being defined. The implementation of find will work with primitive types as well as with any user defined type that has an equality operator defined. There is a common single interface that makes sense. Compare that with the Java version, where comparison of object types must be performed through the .equals member function, while comparing primitive types can be done with ==. By allowing you to overload the operators you can work with user defined types in the same way that you can with primitive types.
The same goes for ordering. If there is a well defined (partial) order in the domain of your class, then providing operator< is a simple way of implementing that order. Code will be readable, and your type will be usable in all situations where a partial order is required, as inside associative containers:
bool operator<( type const & lhs, type const & rhs )
{
return lhs < rhs;
}
std::map<type, int> m; // m will use the natural `operator<` order
A common pitfall when operator overloading was introduced into the language is that of the 'golden hammer' Once you have a golden hammer everything looks like a nail, and operator overloading has been abused.
It is important to note that the reason for overloading in the first place is improving readability. Readability is only improved if when a programmer looks at the code, the intentions of each operation are clear at first glance, without having to read the definitions. When you see that two complex numbers are being added like a + b you know what the code is doing. If the definition of the operator is not natural (you decide to implement it as adding only the real part of it) then code will become harder to read than if you had provided a (member) function. If the meaning of the operation is not well defined for your type the same happens:
MyVector a, b;
MyVector c = a + b;
What is c? Is it a vector where each element i is the sum of of the respective elements from a and b, or is it a vector created by concatenating the elements of a before the elements of b. To understand the code, you would need to go to the definition of the operation, and that means that overloading the operator is less readable than providing a function:
MyVector c = append( a, b );
The set of operators that can be overloaded is not restricted to the arithmetic and relational operators. You can overload operator[] to index into a type, or operator() to create a callable object that can be used as a function (these are called functors) or that will simplify usage of the class:
class vector {
public:
int operator[]( int );
};
vector v;
std::cout << v[0] << std::endl;
class matrix {
public:
int operator()( int row, int column );
// operator[] cannot be overloaded with more than 1 argument
};
matrix m;
std::cout << m( 3,4 ) << std::endl;
There are other uses of operator overloading. In particular operator, can be overloaded in really fancy ways for metaprogramming purposes, but that is probably much more complex than what you really care for now.
Another use of operator overloading, AFAIK unique to C++, is the ability to overload the assignment operator. If you have:
class CVector
{
// ...
private:
size_t capacity;
size_t length;
double* data;
};
void func()
{
CVector a, b;
// ...
a = b;
}
Then a.data and b.data will point to the same location, and if you modify a, you affect b as well. That's probably not what you want. But you can write:
CVector& CVector::operator=(const CVector& rhs)
{
delete[] data;
capacity = length = rhs.length;
data = new double[length];
memcpy(data, rhs.data, length * sizeof(double));
return (*this);
}
and get a deep copy.
Operator overloading allows you to give own meaning to the operator.
For example, consider the following code snippet:
char* str1 = "String1";
char* str2 = "String2";
char str3[20];
str3 = str1 + str2;
You can overload the "+" operator to concatenate two strings. Doesn't this look more programmer-friendly?