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

#1fndef COMPLEXH - #define COMPLEXH class complex public: - protected: double re

ID: 3906287 • Letter: #

Question

#1fndef COMPLEXH - #define COMPLEXH class complex public: - protected: double real; double imag #endif Modify the class declaration above to include the following PUBLIC methods: The Orthodox Canonical Form (OCF); You may implement the trivial methods in the declaration Accessor Functions; A class method which takes a reference to another instance of the class as a parameter and calculates the magnitude of the vector between the two instances. The method may not modify . either instance in any way.

Explanation / Answer

This question asked us to answer following:

1. Orthodox Canonical Form means we have to declare and implement a default constructor, a copy constructor, the assignment operator and a destructor.

2. Accessor Functions means getter and setter functions which can get or set the values of member variables.

3. Class function which calculates magnitude of the vector between two instances of the complex class. This can be calculated using sqrt((x1-x2)^2 + (y1-y2)^2).

Find the code below for all three functions.

#include <cmath>

#include<iostream>

using namespace std;

#ifndef COMPLEX_H

#define COMPLEX_H

class complex

{

public:

complex() {

setReal(0);

setImag(0);

}

complex(double r, double i){

setReal(r);

setImag(i);

}

complex(complex& c) {

real = (&c)->getReal();

imag = (&c)->getImag();

}

~complex() {

delete &real;

delete &imag;

}

complex& operator=(complex c) {

this->swap(c);

return *this;

}

void swap(complex &c) {

swap(real, c.real);

swap(imag, c.imag);

}

void swap(double a, double b){

double temp = a;

a = b;

b = temp;

}

// Accessor functions

double getReal() {

return real;

}

void setReal(double r) {

real = r;

}

double getImag() {

return imag;

}

void setImag(double i) {

imag = i;

}

// Declaring non-trivial method magnitudeVector

double magnitudeVector(complex* c);

protected:

double real;

double imag;

};

#endif

double complex::magnitudeVector(complex* c) {

double diff_x = this->real - c->real;

double diff_y = this->imag - c->imag;

double mag = sqrt(diff_y*diff_y + diff_x*diff_x);

return mag;

}

int main() {

complex* c1 = new complex(2, 3);

complex* c2 = new complex(3, 4);

cout << c1->magnitudeVector(c2) << endl;

return 0;

}

Compiler Directives

First save this code as complex.cpp.

Compile the code using g++ command : g++ complex.cpp

Now, run the output using this command: ./a.out

Expected Output: 1.41421 (Magnitude)