Using overloaded operators on this instance (this) within a class method - c++

I am writing a class for a 2D Vector and need to do a dot product.
I have overloaded the * operator to do this, but when it comes time to perform this * this it gives me an error:
class Vector2 {
private:
float x, y;
public:
Vector2(float _x, float _y) {
x = _x;
y = _y;
}
// Dot product
float operator*(const Vector2& other) {
return x * other.x + y * other.y;
}
// Magnitude (abs)
float Magnitude() {
float dot = (this) * (this); // HERE IS THE ERROR: expression must have arithmetic or unscoped enum type
return std::sqrt(dot);
}
Vector2 operator+(const Vector2& other) {
return Vector2(x + other.x, y + other.y);
}
};
The error is: expression must have arithmetic or unscoped enum type
Any help is appreciated! Thank You :)

The this keyword is a pointer, not an actual object.
The correct code is therefore (*this) * (*this).

Related

Using member functions in operator overloading definition (error with const)

I am getting error in the operator overloading definition. The error goes away if I remove the consts in the parameters. Is there any way I can get it working without removing the consts in the parameters? Also what is happening behind them?
class Vector3D{
public:
float x, y, z;
float dot(Vector3D& v) {
return x * v.x + y * v.y + z * v.z;
}
};
inline float operator *(const Vector3D& a, const Vector3D& b) {
return a.dot(b);
}
You should qualify the member function dot as const as well, otherwise you can't call this member function on a const object:
float dot(Vector3D const& v) const { // <-- const here
You also need to accept v by const& since you are passing it a const object.
You didn't include the error, but it says something like : "cannot call non-const method on const object". Your dot does not modify members and should be declared as const also the argument is not modifed, hence should be const:
class Vector3D{
public:
float x, y, z;
// v---------------- allow to call on const objects
float dot(const Vector3D& v) const {
// ^---------------------------------- pass parameters as const ref
return x * v.x + y * v.y + z * v.z;
}
};
inline float operator *(const Vector3D& a, const Vector3D& b) {
return a.dot(b);
}
In the Vector3D::dot function, neither the object for member function call nor the argument object are modified.
To tell this to the compiler, you should add two consts to your dot definition.
class Vector3D{
public:
float x, y, z;
float dot(const /*(1)*/ Vector3D& v) const /*(2)*/ {
return x * v.x + y * v.y + z * v.z;
}
};
inline float operator *(const Vector3D& a, const Vector3D& b) {
return a.dot(b);
}
(1) : telling that the argument object is not modified
(2) : telling that the object for member function call is not modified

error when calling operator inside FUNCTION const

now i am stumbling with c++ code problem.
i made a simple structure 'Vector3' in that i defined the operator+.
and when i use that operator inside const function, it show a red line.
struct Vector3 {
float x, y, z;
Vector3 operator+ (const Vector3 v) {
return Vector3(x + v.x, y + v.y, z + v.z);
};
Vector3(float x, float y, float z) : x(x), y(y), z(z) {};
};
// and i use it inside some const function
struct SomeST {
Vector3 a,b;
Vector3 Function() const
{
return a + b; // error
}
};
and if i delete the const from function, it works!
so it would be amazing if someone can explain what's going on under the hood.
thanks.
Function
Vector3 Function() const
is const. Which means, that this is const inside the function. Which in turn means both a and b are const. a + b syntax is fancy way for writing a.operator + (b) (call operator + method on object a with argument b). Now a is const, so a.operator + method must also be const. Since you've not supplied such operator (the operator you've written is not const) your compiler highlights this as error and if you try to compile it, you will get const based error.
You need to suply operator + (...) const, which in this exact case means you need to add const keyword to definition:
Vector3 operator+ (const Vector3 v) const { ... }

Overloading operator* ambigious with operator double()

g++ can't compile this program because:
"
45:20: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
xxx.cpp:27:15: note: candidate 1: const Point2d Point2d::operator*(float) const
const Point2d Point2d::operator*(float xy) const
xxx.cpp:45:20: note: candidate 2: operator*(double, int) <built-in>
Point2d x = xxx * 3;
"
When I delete "operator double()" then "operator *" works, but is there an option to have those to operators at once?
code:
class Point2d {
public :
Point2d(float x, float y);
const Point2d operator*(float xy) const;
operator double(); //when I delete operator double(), then operator* works
private :
float x;
float y;
};
Point2d::operator double()
{
return sqrt((this->x * this->x) + (this->y * this->y));
}
const Point2d Point2d::operator*(float xy) const
{
return Point2d(x * xy, y * xy);
}
Point2d::Point2d(float x, float y)
{
this->x = x;
this->y = y;
}
int main()
{
Point2d xxx(3, 5.5);
Point2d x = xxx * 3;
return 0;
}
In xxx * 3 the compiler can either convert 3 to float and use operator*(float xy) or convert xxx to double using operator double() and then use the built-in multiplication.
The rules say that this is ambiguous, so it is not allowed to choose either.
When you remove the conversion, one of the options goes away and so it is no longer ambiguous.

How to overload an operator for integer, float and double data types simultaneously in C++

I'm creating a 2D coordinate class (named “Point”) to help me learn C++. I want to be able to perform basic arithmetic operations (+, -, *, / ...) on Point class objects (e.g. Point_a + Point_b). However, I also want to be able to perform such operations between Points and other variable types (int/float/double).
This can be done using operator/function overloading. It can be seen from my code below (addition only) that I must, as far as I am aware, include two additional functions for each additional variable type, one for the “Point + int/float/double” form and one for the “int/float/double + Point” form.
#include <iostream>
using namespace std;
class Point
{
private:
double x, y;
public:
Point(double x_in, double y_in){
setX(x_in);
setY(y_in);
}
// Getters and Setters omitted for brevity
// --- Start of Addition Operator Overloads --- (Code Block A)
friend Point operator+(const Point &p1, const Point &p2); //Point + Point
friend Point operator+(const Point &p1, int val); //Point + Int
friend Point operator+(int val, const Point &p1); //Int + Point
friend Point operator+(const Point &p1, float val); //Point + Float
friend Point operator+(float val, const Point &p1); //Float + Point
friend Point operator+(const Point &p1, double val); //Point + Double
friend Point operator+(double val, const Point &p1); //Double + Point
// --- End of Addition Operator Overloads --- (Code Block A)
};
// --- Start of Addition Operator Overload Functions --- (Code Block B)
Point operator+(const Point &p1, const Point &p2){
return Point(p1.x + p2.x, p1.y + p2.y);
}
Point operator+(const Point &p1, int val){
return Point(p1.x + val, p1.y + val);
}
Point operator+(int val, const Point &p1){
return Point(p1.x + val, p1.y + val);
}
Point operator+(const Point &p1, float val){
return Point(p1.x + val, p1.y + val);
}
Point operator+(float val, const Point &p1){
return Point(p1.x + val, p1.y + val);
}
Point operator+(const Point &p1, double val){
return Point(p1.x + val, p1.y + val);
}
Point operator+(double val, const Point &p1){
return Point(p1.x + val, p1.y + val);
}
// --- End of Addition Operator Overload Functions --- (Code Block B)
int main()
{
Point point_a( 2.00, 20.00);
Point point_b( 0.50, 5.00);
Point point_c = point_a + point_b;
cout << "X = " << point_c.getX() << " and Y = " << point_c.getY() << endl;
return 0;
}
There seems to be a lot of repetition, particular between “Point + int/float/double” type functions. I was wondering if there is a way that this could be shorted a little. Say, rather than having individual versions for integer, float and double I could have one version which would handle all three. For example converting code blocks "A" and "B" into something like:
...
// --- Start of Addition Operator Overloads --- (Code Block A)
friend Point operator+(const Point &p1, const Point &p2); //Point + Point
friend Point operator+(const Point &p1, int||float||double val); //Point + Int/Float/Double
friend Point operator+(int||float||double val, const Point &p1); //Int/Float/Double + Point
// --- End of Addition Operator Overloads --- (Code Block A)
...
...
// --- Start of Addition Operator Overload Functions --- (Code Block B)
Point operator+(const Point &p1, const Point &p2){
return Point(p1.x + p2.x, p1.y + p2.y);
}
Point operator+(const Point &p1, int||float||double val){
return Point(p1.x + val, p1.y + val);
}
Point operator+(int||float||double val, const Point &p1){
return Point(p1.x + val, p1.y + val);
}
// --- End of Addition Operator Overload Functions --- (Code Block B)
...
The above code section is intended to be representational of the desired result rather than actually functional (e.g. int OR float OR double).
In short, is there any way that I can make "friend Point operator+(const Point &p1, int val);" and its corresponding function (in code block B) accept integer, float and double values, or do I need to have an individual one for each variable type?
Thank you for your time.
Other answers mention templates but in actual fact, all numeric types will automatically be promoted to doubles.
Therefore, you only need to provide operators in terms of Point and double.
#include <iostream>
using namespace std;
class Point
{
private:
double x, y;
public:
Point(double x_in, double y_in){
setX(x_in);
setY(y_in);
}
// Getters and Setters omitted for brevity
double getX() const { return x; }
double getY() const { return y; }
void setX(double v) { x = v; }
void setY(double v) { y = v; }
// unary ops
Point& operator+=(Point const& other)
{
x += other.x;
y += other.y;
return *this;
}
Point& operator+=(double v)
{
x += v;
y += v;
return *this;
}
// --- Start of Addition Operator Overloads --- (Code Block A)
friend Point operator+(Point p1, const Point &p2)
{
p1 += p2;
return p1;
}
friend Point operator+(Point p1, double val)
{
p1 += val;
return p1;
}
friend Point operator+(double val, Point p1)
{
p1 += val;
return p1;
}
// --- End of Addition Operator Overloads --- (Code Block A)
};
// --- End of Addition Operator Overload Functions --- (Code Block B)
int main()
{
Point point_a( 2.00, 20.00);
Point point_b( 0.50, 5.00);
Point point_c = point_a + point_b;
point_c += 10;
Point point_d = point_c + 10;
Point point_e = point_d + 10.1;
cout << "X = " << point_c.getX() << " and Y = " << point_c.getY() << endl;
return 0;
}
Such can be more generalized by using templates and specializing the exceptional case, instead of providing an overloaded version for each and every matching type:
class Point
{
public:
// ...
template<typename T>
friend Point operator+(const Point &p1, T p2);
};
template<typename T>
Point operator+(const Point &p1, T val){
static_assert(std::is_artithmetic<T>::value,"An arithmetic type is required");
return Point(p1.x + val, p1.y + val);
}
// Specialization for Point
template<>
Point operator+(const Point &p1, const Point& val){
return Point(p1.x + val, p1.y + val);
}
Separate solution than the template solution is to define constructors for the types you want to support, and have a single operator+ that works on Point types.
The compiler will implicitly call the proper constructor to convert the built-in type, before invoking operator+.
This simplifies the implementation, at the expense of wasted temp objects.
// Example program
#include <iostream>
#include <string>
class Point {
private:
double x, y;
public:
Point(int val) {
this->x = val;
this->y = val;
}
Point(double x, double y) {
this->x = x;
this->y = y;
}
friend Point operator+(const Point &p1, const Point &p2) {
return Point(p1.x + p2.x, p1.y + p2.y);
}
};
int main()
{
Point p(1,2);
Point q = p + 10;
Point v = 10 + p;
}
There is a stylistic argument about explicitly white-listing supported types via the constructors, and blacklisting via static_asserts.
You can absolutely do this using templates:
// inside the class
template <typename T, std::enable_if_t<std::is_arithmetic_v<T>, int> = 0>
friend Point operator+(const Point &p1, T val) {
// function definition
}
// Don't forget to define the function for T on the left hand side
This uses std::enable_if and std::is_arithmetic, to make this function only accept types that are "arithmetic types", basically integers and floats.
Point's operator+ implementations all converts its non-Point arguments to doubles before doing a + on elements.
The float and int overloads are nearly pointless. Just write the two double overloads.
Built-in conversion from int and float will then occur in the operator+ call.
If you really need int/float overloads and you know why and have tested that the double overload doesn't work, consider fixing the broken template conversion operator which is about the only way I can see this bbeing the case.
Failing that, cast to double explicitly.
Failing that, maybe write a template + that takes any T convertible to double, then converts and calls the above + for double. Then add a paragraph of documentation why you had to do something this stupid and complex instead of just overloading + with double. Then read that paragraph and change your mind and stick with + overloaded with double.

How does this operator [ ] overloading works in this case?

I stumbled upon this class:
class Vec3f
{
...
float x, y, z;
...
};
inline float operator[](const int index) const
{
return (&x)[index];
}
inline float& operator[](const int index)
{
return (&x)[index];
}
The class is using the [] to access to x, y, z values as in an array so that
v[0] is the value in x, v[1] is the value in y, v[2] is the value in z, but
How does the return statement working?
Is it correct to read it like: "get the value in the address specified by index starting from the address of x"?
Do (&x) must be in parenthesis, otherwise it would return the value of the address of x[index], isn't it?
Technically this is not valid code.
But what is happening:
// Declare four variables
// That are presumably placed in memory one after the other.
float x, y, z;
In the code:
return (&x)[index];
// Here we take the address of x (thus we have a pointer to float).
// The operator [] when applied to fundamental types is equivalent to
// *(pointer + index)
// So the above code is
return *(&x + index);
// This takes the address of x. Moves index floating point numbers further
// into the address space (which is illegal).
// Then returns a `lvalue referring to the object at that location`
// If this aligns with x/y/z (it is possible but not guaranteed by the standard)
// we have an `lvalue` referring to one of these objects.
Its easy to make this work and be legal:
class Vec3f
{
float data[3];
float& x;
float& y;
float& z;
public:
float& operator[](const int index) {return data[index];}
Vec3f()
: x(data[0])
, y(data[1])
, z(data[2])
{}
Vec3f(Vec3f const& copy)
: x(data[0])
, y(data[1])
, z(data[2])
{
x = copy.x;
y = copy.y;
z = copy.z;
}
Vec3f& operator=(Vec3f const& rhs)
{
x = rhs.x;
y = rhs.y;
z = rhs.z;
return *this;
}
};