C++ overloading + operator not working - c++

Hello guys look to my code I'm trying to make a program which asks you to enter the first value by grams And the second value is kilograms and then convert kilograms to grams by an overloaded + operator but it doesn't work why
#include <iostream>
using namespace std;
class ADD{
private:
int Fval;
int Sval;
public:
ADD(){
cout << "WELCOME TO OUR PROGRAM"<<endl<<"PLEASE ENTER THE FIRST VALUE BY GRAMS :";
cin >> Fval;
cout << "PLEASE ENTER THE SECOND VALUE BY KILOGRAMS :"; cin >> Sval;
}
ADD operator+(ADD& add){
add.Sval *= 1000;
return add;
}
int plus(){
return Fval+Sval;
}
};
int main(){
ADD a1;
cout << "THE TOTAL VALUE = " << a1.plus() << " GRAMS";
}
No Effect look to the output
WELCOME TO OUR PROGRAM
PLEASE ENTER THE FIRST VALUE BY GRAMS :2
PLEASE ENTER THE SECOND VALUE BY KILOGRAMS :3
THE TOTAL VALUE = 5 GRAMS
That means the + operator doesn't multiply 3 by 1000
Why??

That's because you're not calling operator +.
You're calling ADD::plus():
int plus(){
return Fval+Sval;
}
Fval and Sval are integers, which you're adding up. It's as simple as that.
EDIT:
Your code is fishy.
ADD operator+(ADD& add){
add.Sval *= 1000;
return add;
}
Multiplication inside operator +? Really? Also, not that you're modifying the parameter, which you shouldn't. It's not intuitive. If you really must do this:
ADD operator+(const ADD& add){
ADD ret;
ret.Sval = add.Sval * 1000;
return ret;
}

The way operator overloading works is that if you have an object of type X, like so:
class X {
public:
X( int v ) : x( v ) {}
int value();
X operator +( const X& y ) {
return X( value() + y.value() );
}
private:
int y;
};
Now if you declare two objects of type X, say X ex and X wye, you can say
X zed = ex + wye;
and get the right result. If type X had more than just a single int field the effect would be more interesting. For example, you could implement 2D vectors and points, and then operations that add and subtract vectors, to get vectors, add and subtract vectors to/from points to get points, and subtract points to get vectors.
Hopefully this will give you enough of an idea of what's going on to be able to restructure your code to get it to do what you want. I may have a detail of syntax wrong, as I'm typing as I go.
Also, I often find the right thing is to declare a friend operator when I want a binary operator:
friend operator + ( vector2D a, vector2D b );
...
inline operator + ( vector2D a, vector 2D b ) {
return vector2D ( a.x + b.x, a.y + b.y );
}

Related

C++ Fraction Calculator using Classes and Functions

I am new to StackOverflow, and starting at a new school. I was hoping for some guidance on an assignment. The assignment is to calculate an expression involving two fractions, and output the result. I've been working on this program for days with the knowledge from my textbook, but I guess I am still confused on how to implement functions within a class. I know what I want to do with my values, but I am confused on where to assign them. I tried to read in my values, but when outputting, I get garbage. Any help would be greatly appreciated.
#include <iostream>
using namespace std;
class fraction // Fraction class definition
{
int num,
den;
public:
fraction() // default constructor
{
num = 0;
den = 1;
}
void add(fraction f1, fraction f2) // addition fcn
{
num = (f1.num*f2.den) + (f2.num*f1.den);
den = f1.den*f2.den;
}
void subtract(fraction f1, fraction f2) // subtraction fcn
{
num = (f1.num*f2.den) - (f2.num*f1.den);
den = f1.den*f2.den;
}
void multiply(fraction f1, fraction f2) // multiplying fcn
{
num = f1.num*f2.num;
den = f1.den*f2.den;
}
void divide(fraction f1, fraction f2) // dividing fcn
{
num = f1.num*f2.den;
den = f1.den*f2.num;
}
void output()
{
cout << num << "/" << den << endl;
}
}; // end Fraction class
int main()
{ // begin main
fraction result;
fraction n;
fraction d;
int n1, n2, d1, d2 = 0;
char op;
cout << "Please enter an expression containing two fractions:" << endl;
cin >> n1 >> d1 >> op >> n2 >> d2;
switch (op)
{ // begin switch
case '+':
result.add(n, d);
result.output();
break;
case '-':
result.subtract(n, d);
result.output();
break;
case '*':
result.multiply(n, d);
result.output();
break;
case'/':
result.divide(n, d);
result.output();
break;
} // end switch
//fraction f1(n1, d1);
//fraction f2(n2, d2);
} // end main
The actual answer was given in the very first comment of John3136. Hence, I struggled a bit but finally realized that you probably didn't recognize. So, I will elaborate this a bit:
In main(), you do this:
int n1, n2, d1, d2 = 0;
char op;
cout << "Please enter an expression containing two fractions:" << endl;
cin >> n1 >> d1 >> op >> n2 >> d2;
Stepping through with a debugger, you will realize that this part of program works as expected. After input of e.g.
1 2 + 3 4
the variables will show the following values:
n1: 1
d1: 2
n2: 3
d2: 4
op: '+'
Live demo on ideone
Stepping further, the program pointer will move to
result.add(n, d);
Hmm. You want to add n and d but the debugger says:
n: { num: 0, den: 1 }
d: { num: 0, den: 1 }
The values of n.num, n.den, d.num, and d.den are there as you provided a default constructor for class fraction which effects precisely this.
So, how do you think will n1 be moved to n.num, d1 to n.den, and so on?
What's really missing is a constructor for class fraction to load members num and den (in this case of n and d) with the specified values.
You could introduce a second constructor. In this case, you can modify (and extend) your existing, also:
class fraction {
private:
int num, den; // numerator, denominator
public:
explicit fraction(int num = 0, int den = 1): num(num), den(den) { }
};
Looks confusing? I will explain:
I gave the constructor arguments, but the arguments got default values.
Hence, it still can be used as default constructor. Doing fraction a; will construct fraction 0/1 as before. But, now, you can also do fraction b(3, 2); to construct fraction 3/2. You can even do fraction d(3);. This will construct fraction 3/1 which sounds reasonable to me.
I named the arguments equal to the members. Looks funny and, may be, a bit confusing but it seems to be very usual nowadays. (Actually, I learned this in SO a short time ago.) However, the compiler will understand this correctly (even if it is the one of MS).
I prefixed the constructor with explicit. This prevents that the constructor might be used for implicit conversion. Without explicit, the following would work as well: fraction c; c = 1; i.e. assignment of class fraction from an int. This is a question of design whether or not you want to support this. Implicit conversion can be quite convenient but the compiler might apply it where you don't expect it. I personally got used to make nearly every constructor explicit as I don't like to "lose control" of what the compiler is doing.
Modifying the above constructor as recommended you then can use your class, e.g.:
fraction a(3, 2), b(1, 2);
fraction result; result.add(a, b);
result.output();
Now, it should print the sum of fractions a and b.
A last note:
I consider O'Neil's hint with the operator overloading basically reasonable. You will find answers with code samples in SO. (Some of them, written by me.) ;-) On the other hand, operator overloading is just another handicap. I wouldn't bother too much about this. (May be, in a second version...)
Finally, I made an MCVE to demonstrate the above mentioned with sample code:
#include <iostream>
using namespace std;
class fraction {
private:
int num, den; // numerator, denominator
public:
explicit fraction(int num = 0, int den = 1): num(num), den(den) { }
void add(fraction f1, fraction f2) // addition fcn
{
num = (f1.num * f2.den) + (f2.num * f1.den);
den = f1.den * f2.den;
}
void output() { cout << num << "/" << den << endl; }
};
int main()
{
fraction a0;
cout << "fraction a0: "; a0.output();
fraction a(3, 2), b(1);
cout << "fraction a(3, 2): "; a.output();
cout << "fraction b(1): "; b.output();
fraction c; c.add(a, b);
cout << "fraction c = a + b: "; c.output();
// assignment (using default assignment operator)
fraction d; d = c;
cout << "faction d = c; d: "; d.output();
#if 0 // disabled code
// This will work only if constructor is not explicit:
fraction e = 1; e = 1;
cout << "fraction e; e = 1; e: "; e.output();
#endif // 0
// fraction from input
int n1, n2;
cout << "Input n1 n2: "; cin >> n1 >> n2;
fraction in(n1, n2);
cout << "fraction in(n1, n2): "; in.output();
// done
return 0;
}
Input:
123 321
Output:
fraction a0: 0/1
fraction a(3, 2): 3/2
fraction b(1): 1/1
fraction c = a + b: 5/2
faction d = c; d: 5/2
Input n1 n2: fraction in(n1, n2): 123/321
Live demo on ideone.
After having read your comment, I'm in doubt whether you already understood the concept of class and member function. I'll try my best:
Are you aware that your function add() is a member function? It is as you defined the function inside your class fraction. That means, add() cannot be called without an object (i.e. an instance of fraction).
If you write this into your main() function you get a compiler error:
fraction a, b;
fraction::add(a, b);
Live demo on ideone
The object is another argument that a call of a (non-static) member function (like fraction::add()) urgently needs. May be, you didn't recognize the thing in front of the dot as function argument but it is.
fraction c; c.add(a, b);
/* ^ ^ ^
* | | +--- 2nd argument
* | +------ 1st argument
* +------------ object (which becomes THE this POINTER inside fraction::add())
*/
Hence, fraction.add() has actually three arguments. So, how may the object be accessed? For this, C++ provides a special keyword this. this is a pointer to class, and it provides a pointer to the object for which the member function has been called. Using this, you can access all (other) members of this class – member variables as well as member functions.
(Decades ago, when I tried to understand by myself how C++ and OOP are working, I had a look into the compiled assembly code. I was really surprised to realize that the object before the dot was exactly handled like the other arguments in the parentheses. This was one of my personal Heureka!-moments.)
Access to members (of the same class) can be done inside a member function with this-> but it can be left out as well as the compiler will add this silently if applicable.
Your member function fraction::add() is actually a demonstration of this.
It gets two arguments f1 and f2, processes their members (f1.num, f1.den, f2.num, and f2.den) to perform the addition of fractions, and stores the resp. results in member variables num and den. In this case, num is the same as this->num and den the same as this->den. So, where is this pointing to? This depends on the object for which the member function has been called. For e.g.:
result.add(n, d);
inside of fraction::add(), this will point to result.

Scope of Variable in Friend Operator

For one of our class assignments we had to implement a polynomial class. It stores the coefficients of a polynomial and outputs the answer.
In my class definition, I have a friend operator that outputs the function:
friend std::ostream& operator << (std::ostream& out, Polynomial& p);
and my implementation is as follows:
std::ostream& operator << (std::ostream& out, Polynomial& p) {
double ans = 0;
for(int i = 0; i <= p.order; ++i)
ans += (double)p.coefficents[i] * pow(p.x, i);
out << ans;
return out;
}
My main function (written by my instructor) is:
int main ()
{
Polynomial p1 (0.5,3); // Invokes two argument constructor for p1
p1.inputCoefficients(); // Set the coefficient of polynomial p1
cout << "Polynomial p1 evaluates to " << p1 << endl;
Polynomial p2(p1), p3; // Copy constructor for p2 and default constructor for p3
cout << "Polynomial p2 evaluates to " << p2 << endl;
cout << "Polynomial p3 evaluates to " << p3 << endl;
p3 = p2; // Copy assignment operator
return 0;
}
My question is:
When I run my program with this line of code:
double ans = 0;
my output is this:
Polynomial p1 evaluates to 1.375
Polynomial p2 evaluates to 1.375
Polynomial p3 evaluates to 0
Polynomial destroyed!
Polynomial destroyed!
Polynomial destroyed!
Which is the correct output
but if I change that line to this:
double ans;
Unexpected things start to happen:
Polynomial p1 evaluates to 1.375
Polynomial p2 evaluates to 1.375
Polynomial p3 evaluates to 1.375
Polynomial destroyed!
Polynomial destroyed!
Polynomial destroyed!
Why is p3 evaluated to 1.375? p3 was created using the default constructor so wouldn't it output 0?
As soon as the polynomial is outputted wouldn't the scope of ans die? Even if it didn't, or ans kept the value from the last time it ran, then wouldn't p2 be doubled (be 2.75) because the << operator ran twice?
Please feel free to get technical and offer advice, I'm curious and want to know the insides of what's actually going on.
Here is the entirety of my code (for reference):
/*
Using dynamic arrays, implement a polynomial class. In mathematics, polynomial is a function of the form f(x) = a0*x^0 + a1*x^1 + a2*x^2 + a3*x^3 + ....n terms. Here, a0, a1, a2 etc. are the coefficients of the polynomial and n is the order of the polynomial.
The private variables include the value of x (a real number), the order of the polynomial (an integer) and the dynamic array that stores the coefficients (real numbers).
The public methods include
a. default constructor that sets the value of x to zero and the order to 0,
b. a two argument constructor that takes as arguments the value of x and the order of the polynomial. The values of the coefficients are set to zero.
c. inputCoefficients(): prompts the user to input the value of the coefficients of the polynomial. For this homework, skip the user input. Instead assign the coefficent values equal to the index of the position in the array. For example, a0 = 0, a1 = 1, a2 = 2 and so on depending on the order of the particular polynomial object
c. a copy constructor
d. << operator overloaded that returns the value of the polynomial (obtained by evaluating the polynomial).
e. == overloaded (copy assignment operator)
f. destructor. Deallocates dynamic arrays and prints a message "Polynomial destroyed! "
Below is the testing program -
*/
#include <iostream>
using std::cin;
using std::endl;
using std::cout;
#include <cmath>
class Polynomial {
public:
Polynomial() {
x = 0,
order = 0;
coefficents = new double[order + 1];
}
Polynomial(const double x, const int order) {
this->x = x;
this->order = order;
this->coefficents = new double[order + 1];
for(int i = 0; i <= order; ++i)
this->coefficents[i] = 0;
}
Polynomial(const Polynomial& p) {
this->x = p.x;
this->order = p.order;
this->coefficents = new double[this->order];
for(int i = 0; i <= this->order; ++i)
this->coefficents[i] = p.coefficents[i];
}
~Polynomial() {
std::cout << "Polynomial destroyed! " << std::endl;
delete[] coefficents;
}
void inputCoefficients() {
/*
for(auto& num: coefficents) {
std::cout << "Enter the next coefficent:: ";
std::cin >> num;
}
std::cout << "Thank you" << std::endl;
*/
for(int i = 0; i <= order; ++i) {
coefficents[i] = i;
}
}
Polynomial& operator = (const Polynomial& p) {
this->x = p.x;
this->order = p.order;
delete[] this->coefficents;
this->coefficents = new double[order + 1];
for(int i = 0; i <= this->order; ++i)
this->coefficents[i] = p.coefficents[i];
return *this;
}
friend std::ostream& operator << (std::ostream& out, Polynomial& p);
friend bool operator == (const Polynomial& p1, const Polynomial& p2);
private:
double x;
double* coefficents;
int order;
};
std::ostream& operator << (std::ostream& out, Polynomial& p) {
double ans;
for(int i = 0; i <= p.order; ++i)
ans += (double)p.coefficents[i] * pow(p.x, i);
out << ans;
return out;
}
bool operator == (const Polynomial& p1, const Polynomial& p2) {
if((p1.x != p2.x) && (p1.order != p2.order))
return false;
for(int i = 0; i < p1.order; ++i) {
if(p1.coefficents[i] != p2.coefficents[i])
return false;
}
return true;
}
int main ()
{
Polynomial p1 (0.5,3); // Invokes two argument constructor for p1
p1.inputCoefficients(); // Set the coefficient of polynomial p1
cout << "Polynomial p1 evaluates to " << p1 << endl;
Polynomial p2(p1), p3; // Copy constructor for p2 and default constructor for p3
cout << "Polynomial p2 evaluates to " << p2 << endl;
cout << "Polynomial p3 evaluates to " << p3 << endl;
p3 = p2; // Copy assignment operator
return 0;
}
Your << function contains the line:
ans += (double)p.coefficents[i] * pow(p.x, i);
If you don't initialize ans to 0, then the initial value of ans will be indeterminate, and then you're adding each term to this. So you get a random result.
In your case, ans is apparently holding on to its value from the previous call. And since p3 is an empty polynomial, the loop never adds anything to it, so you print the previous result.

2D vector ignores assigned values?

I'm working on a simple class representing polynomials. I store coefficients and equivalent powers of x in 2D vector. The way of assigning certain terms must be as shown in the test file. It equires some operator overloading which i provided. The problem is that it assigns proper coefficients besides last one, additionally every terms has power of x of the first assigned value.
Desired output:
Polynomial p1: 2x^3 + 3.6x + 7x^0
Polynomial p2: 3x^1 + 6x^2 + 1x^4
Actual output:
Polynomial p1: 5x^3 + 2x^3 + 3.6x^3
Polynomial p2: 5x^1 + 3x^1 + 6x^1
Have you got any idea what is the case? I
Polynomials.cpp
double & Polynomials::operator[]( int power_of_x ){
this->coeff_and_power.push_back(5.0); // dummy variable 5.0 just to alloc 'cell' for coefficient
this->coeff_and_power.push_back( (double) power_of_x ); //assigning power of x
this->polynomial_terms.push_back( coeff_and_power ); // polynomial_terms vector contains collection of 2 elements vectors( coefficient and power ) indicating certain term of a function
return (coeff_and_power[0]); //coefficient to be assigned in main(returning by reference) function
}
std::ostream& operator<<(std::ostream& out, const Polynomials & toWrite){
for(unsigned int i = 0; i < toWrite.polynomial_terms.size(); i++){
if(i){
out<<" + ";
}
out<<toWrite.polynomial_terms[i][0]<<"x^"<<toWrite.polynomial_terms[i][1];
}
return out;
}
test.cpp
#include <iostream>
#include "Polynomials.h"
using namespace std;
int main(void) {
Polynomials p1;
p1[3] = 2; p1[1] = 3.6; p1[0] = 7;
Polynomials p2;
p2[1] = 3; p2[2] = 6; p2[4] = 1;
cout << "Polynomial p1: " << p1 << endl;
cout << "Polynomial p2: " << p2 << endl;
}
In your operator[] overload you push_back(), but unconditionally.
return coeff_and_power[0];
return front for assignment
And btw this
this->polynomial_terms.push_back( coeff_and_power )
pushes a copy, not a reference, given polynomial_terms has behavior like e.g. std:vector.

How to implement greatest common divisor to simplify fractions

#include <iostream>
using namespace std;
int g_c_d(int n, int d);
class Fraction
{
private:
//variables to store numerator and denominator
int num;
int denom;
public:
Fraction(){}
Fraction(int num): num(num) {}
Fraction(int num, int denom): num(num), denom(denom) {}
void set_num(int n){ num = n;}
void set_denom(int d){ denom = d;}
int get_numerator() const {return num;}
int get_denominator() const {return denom;}
};
int g_c_d(int n, int d){
return d == 0? n : g_c_d(d, n % d);
}
istream &operator>> (istream &input, Fraction &f)
{
int n, d;
char slash;
input >> n;
input >> slash;
input >> d;
if (d == 0) {n = 0;} //if denom is 0; fraction = 0/0
f = Fraction(n, d);
return input;
}
ostream &operator<<(ostream &output, const Fraction &frac)
{
return output << frac.get_numerator() << "/" << frac.get_denominator();
}
int main()
{
int n, d;
Fraction frac;
int gcd;
n = frac.get_numerator();
d = frac.get_denominator();
gcd = g_c_d(frac.get_numerator() , frac.get_denominator());
cout << "Enter a fraction" << endl;
cin >> frac;
frac.set_num(n/gcd);
frac.set_denom(d/gcd);
cout << "your fraction is: ";
cout << frac << endl;
return 0;
}
Hi im trying to simplify fractions entered by a user. However everytime I enter a fraction that is to be simplified the output returned is "1/0".
Can some one please help, it'll be massively appreciated!
The problem is that you do all your computations on frac before asking the user to input a fraction — and then you overwrite whatever the user inputs. You need to move this bit:
cout << "Enter a fraction" << endl;
cin >> frac;
much, much higher up.
When you are setting up the code you have:
Fraction frac;
This calls the default constructor for Fraction. Because you never initialized the members in the constructor you get the default initizliation for the int type which is 0. Then:
n = frac.get_numerator();
d = frac.get_denominator();
This makes n and d 0. From that point onwards you are using those values of n and d. These values however are not the values from the user inputted frac but are just the values you get from the defaults. Change your code to read in the user inputted value for frac before you do any calculations.
The main lesson to learn here is to make sure you don't use uninitialized variables. Generally speaking when you compile with all warnings enabled this is the sort of thing that compilers will warn about.
You may be diving by zero because the default constructor doesn't assign value to the denominator. In the case where the denominator is set to zero, the gcd() function will divide by zero, on the first time in main.

Box2D vector () operator

I was reading the Box2D source code. In b2Vec2 there is the () operator being overloaded, but I did not understand what it is supposed to do. I read the manual and the reference of this method but still did not get what it means to Read from an indexed element and write to an indexed element, and both methods have the same body return (&x)[i]. What does this mean and do?
Thanks to a previous comment (but it was removed for some reason), I got an idea and tested it out, and it turns out this will allow me to access and write to x and y using indices 0 and 1 respectively.
For example:
#include <iostream>
using namespace std;
class clazz {
public:
float x, y;
clazz(float x_, float y_) : x(x_), y(y_) {}
float operator () (int i) const {
return (&x)[i];
}
float& operator () (int i) {
return (&x)[i];
}
};
int main() {
clazz f (3, 4);
cout << "f: x = " << f(0) << " y = " << f(1) << endl; // printed => f: x = 3 y = 4
f(0) = 6;
f(1) = 6;
cout << "f: x = " << f(0) << " y = " << f(1) << endl; // printed => f: x = 6 y = 6
return 0;
}
As you found out it's an accessor function to the individual elements in the vector class. The reason there are two functions is due to const functions need access to the value of the element without needing to modify it. Note that you could return a const reference here as well but this is not necessary in your case since it is operating on a float.
Hopefully there are asserts in place for making sure that code isn't indexing out of the range since that is quite easy to do, especially when you have are using a signed variable like in your example.