Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator keyword c++

We have following class. I need explanation of some parts of code.

class CPoint3D
    {
    public:
      double x, y, z;

      CPoint3D (double dX = 0.0, double dY = 0.0, double dZ = 0.0) 
              : x(dX), y(dY), z(dZ) {}
      //what means these lines of    code?
      CPoint3D operator + (const CPoint3D& point) const;
      CPoint3D operator - (const CPoint3D& point) const;
      CPoint3D operator * (double dFactor) const;
      CPoint3D operator / (double dFactor) const;
};

I guess using

CPoint3D operator + (const CPoint3D& point) const;

function I can easily add/subtract/multiply/divide instances of CPoint3D class?

Can someone explain this with examples ? Thanks!

like image 663
Nurlan Avatar asked Aug 16 '13 08:08

Nurlan


People also ask

What is keyword operator?

The operator keyword in C++ The keyword operator is used while overloading operators. The syntax for overloading an operator is the following: return_type operator operator's_symbol(parameters){ //... Your code here... } To learn more about overloading operators in c++ you can refer to my article here.

What is the operator () in C++?

In programming, an operator is a symbol that operates on a value or a variable. Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction.

Is operator overloading in C?

C does not support operator overloading (beyond what it built into the language).


1 Answers

There are millions of examples and/or articles of this on the web (including this one) so I won't re-iterate them here.

Suffice to say that when you add together two CPoint3D objects with obj1 + obj2, the function that gets called is operator+ for that class, with one object being this and the other being point.

Your code is responsible for creating another object containing the addition of those two, then returning it.

Ditto for the subtraction. The multiplicative operators are slightly different since they use a double as the other argument - presumably while it makes some sense to add/subtract individual members of your class for the additive operators, that's not as useful for the multiplicative ones.

like image 146
paxdiablo Avatar answered Sep 27 '22 18:09

paxdiablo