Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Exercise 10. Write a C++ class named point that has three coordinates x , y , an

ID: 3833526 • Letter: E

Question

Exercise 10. Write a C++ class named point that has three coordinates x, y, and z, where the coordinates are private. Create a function which is external to the class that computes the dot product between the coordinates. (Note: How do we access private members? Refer to the lecture slides on classes. Hint: friend functions)

Note: In mathematics, the dot product or scalar product is an algebraic operation that takes two equal-length sequences of numbers (usually coordinate vectors) and returns a single number.

Example:
The dot product of vectors [1, 3,
5] and [4, 2, 1] is: (1)(4) + (3)(-2) + (-5)(-1) =3

Explanation / Answer

#include <iostream>
using namespace std;

class Point
{
    private:
    int x,y,z;
  
    public:
    Point(int x,int y,int z) //constructor
    {
        this->x = x;
        this->y = y;
        this->z = z;
    }
    friend int dotProduct(Point p1,Point p2);//declare friend function
};

int dotProduct(Point p1,Point p2) //define friend function
{
   return (p1.x * p2.x + p1.y * p2.y + p1.z * p2.z);
}
int main()
{
    // create two Point objects
Point p1(1,3,-5);
Point p2(4,-2,-1);

cout<<"Dot product of vectors = "<<dotProduct(p1,p2); //call function dotProduct and display

   return 0;

}

Output:

Dot product of vectors = 3