What is the difference between this two codes for Complex class ?
What is the preference of code that written by pointers ?
Thanks ...
First code with pointers :
//Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex
{
public:
Complex ( double = 1, double = 0 );
void sum ( Complex *, Complex * );
void subtract ( Complex *, Complex * );
void print ( );
private:
double realPart,imaginaryPart;
};
#endif
//Complex.cpp
#include <iostream>
#include "Complex.h"
using namespace std;
Complex::Complex ( double real, double imaginary )
{
realPart = real;
imaginaryPart = imaginary;
}
void Complex::sum ( Complex *c1, Complex *c2 )
{
realPart = c1->realPart + c2->realPart;
imaginaryPart = c1->imaginaryPart + c2->imaginaryPart;
}
void Complex::subtract ( Complex *c1, Complex *c2 )
{
realPart = c1->realPart - c2->realPart;
imaginaryPart = c1->imaginaryPart - c2->imaginaryPart;
}
void Complex::print ( )
{
cout << "( " << realPart << ", " << imaginaryPart << " )";
}
//main.cpp
#include <iostream>
#include "Complex.h"
using namespace std;
int main ( )
{
double real, imaginary;
cout << "Enter first complex :\n";
cin >> real >> imaginary;
Complex *c1 = new Complex ( real, imaginary );
cout << "Enter second complex :\n";
cin >> real >> imaginary;
Complex *c2 = new Complex ( real, imaginary );
Complex *c = new Complex ( );
cout << "Dafault complex is : ";
c->print ( );
cout << "\nSum of two entered complex : ";
c->sum ( c1, c2 );
c->print ( );
cout << "\nSubtract of two entered complex : ";
c->subtract ( c1, c2 );
c->print ( );
cout << endl;
return 0;
}
Second code without pointers :
//Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex
{
public:
Complex ( double = 1, double = 0 );
void sum ( Complex, Complex );
void subtract ( Complex , Complex );
void print ( );
private:
double realPart,imaginaryPart;
};
#endif
//Complex.cpp
#include <iostream>
#include "Complex.h"
using namespace std;
Complex::Complex ( double real, double imaginary )
{
realPart = real;
imaginaryPart = imaginary;
}
void Complex::sum ( Complex c1, Complex c2 )
{
realPart = c1.realPart + c2.realPart;
imaginaryPart = c1.imaginaryPart + c2.imaginaryPart;
}
void Complex::subtract ( Complex c1, Complex c2 )
{
realPart = c1.realPart - c2.realPart;
imaginaryPart = c1.imaginaryPart - c2.imaginaryPart;
}
void Complex::print ( )
{
cout << "( " << realPart << ", " << imaginaryPart << " )";
}
//main.cpp
#include <iostream>
#include "Complex.h"
using namespace std;
int main ( )
{
double real, imaginary;
cout << "Enter first complex :\n";
cin >> real >> imaginary;
Complex c1 ( real, imaginary );
cout << "Enter second complex :\n";
cin >> real >> imaginary;
Complex c2 ( real, imaginary );
Complex c;
cout << "Dafault complex is : ";
c.print ( );
cout << "\nSum of two entered complex : ";
c.sum ( c1, c2 );
c.print ( );
cout << "\nSubtract of two entered complex : ";
c.subtract ( c1, c2 );
c.print ( );
cout << endl;
return 0;
}