1

The program should resolve grade 1 equations in this specific manner. I had to use output messages for the constructors and destructors for better understanding of the code.

#include "stdafx.h"
#include <iostream>

using namespace std;

class Ec {  
public: float a, b;  //equation's parameters
public:
    Ec() {float x, y; cout <<"a= "; cin >> x; cout << "b= "; 
           cin >> y; a = x; b = y; cout << "void constr\n";};
    Ec(float x, float y) { a = x; b = y; cout << "param constr\n"; }
    ~Ec() { cout << "destr\n"; }
    Ec(Ec &z) { a = z.a; b = z.b; cout << "cpy constr\n"; }

friend float half1(Ec); //function to return a/2
friend float half2(Ec); //function to return b/2
friend float sol1(Ec);  //function to return the solution for the standard eq
friend float sol2(Ec);  //function to return the sol for the /2 param eq
};

float half1(Ec ec1) { return (ec1.a / 2);}
float half2(Ec ec1) { return (ec1.b / 2); }

float sol1(Ec ec1) { float x; return x = -ec1.b / ec1.a; }
float sol2(Ec ec1) { float x2; return x2 = -half2(ec1) / half1(ec1); }

int main()
{
    int x, y;
        cout << "a= ";
        cin >> x;
        cout << "b= ";
        cin >> y;
        Ec ec1;
        Ec ec2(x, y);
        Ec ec3 = ec1;
 //the couts display for ex:" ec 2x+1=0 has sol -0.5"
        cout << "ec " << ec1.a << "x+ " << ec1.b << "=0 has sol " << sol1(ec1) << endl;
        cout << "ec " << ec2.a << "x+ " << ec2.b << "=0 has sol " << sol1(ec2) << endl;
        cout << "ec " << ec3.a << "x+ " << ec3.b << "=0 has sol " << sol1(ec3) << endl;

        cout << "ec halved " << half1(ec1) << "x+ " << half2(ec1) << "=0 has sol " << sol2(ec1) << endl;
        cout << "ec halved " << half1(ec2) << "x+ " << half2(ec2) << "=0 has sol " << sol2(ec2) << endl;
        cout << "ec halved " << half1(ec3) << "x+ " << half2(ec3) << "=0 has sol " << sol2(ec3) << endl;
    }
    return 0;
}

Now, I have troubles understanding why after the first cpy constructor(for ec3) another cpy constructor is called then a destructor. What is it doing?

  • Welcome to Stack Overflow. Please take the time to read [The Tour](http://stackoverflow.com/tour) and refer to the material from the [Help Center](http://stackoverflow.com/help/asking) what and how you can ask here. – πάντα ῥεῖ Dec 22 '16 at 14:13
  • 1
    Your functions accept `Ec` by value, so copies are made to be passed in. – AndyG Dec 22 '16 at 14:14

1 Answers1

3

Your functions take Ec objects by value

float half1(Ec ec1) { return (ec1.a / 2);}
            ^

These will make function local copies that are then destroyed at the end of each function.

If you want to avoid making these copies, pass the arguments by const reference

float half1(Ec const& ec1) { return (ec1.a / 2);}
               ^
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218