Matt Corby - 1 month ago 4
C++ Question

# How to initialize a struct with a function in C++?

I want to make a program that does fraction calculations, and i've made a fraction struct with 2 properties: numerator and denominator. I want to be able to initialize those properties using a function i've overloaded twice called

init(fraction x)
. The overloads are as follows:

init(fraction x) //Initializes a fraction struct with numerator and denominator equal to 0
init(fraction x, int a) //initializes fraction struct to a/1
init(fraction x, int a, int b) //initializes fraction struct to a/b

Then I try to test it and output a fraction like so

int main() {

fraction a;
init(a,1);

cout << "The fraction is: ";
print(a);
cout << endl;

return 0;
}

but I just get 0/0 every time no matter what. I think it's a pass by value/reference problem but i'm not sure how to go about fixing this. Here's all my code:

#include <iostream>
using namespace std;

struct fraction {
int numerator = NULL, denominator = NULL;
};

void init(fraction x); // set fraction to 0
void init(fraction x, int n); // set fraction to n/1
void init(fraction x, int a, int b); // set fraction to a/b
fraction add(fraction a, fraction b); // adds a and b and returns the sum (a and b unchanged)
fraction sub(fraction a, fraction b); // subtracts a and b and returns difference
fraction mul(fraction a, fraction b); // multiplies a and b and returns the product
fraction div(fraction a, fraction b); // divides a and b and returns the quotient
void print(fraction x); // prints the fraction (no improper fractions)
void reduce(fraction x); // simplifies x to lowest common terms
int gcd(int a, int b); // finds greatest common divisor of a and b

Source.cpp

void init(fraction x) {
x.numerator = 0;
x.denominator = 0;
}

void init(fraction x, int n) {
x.numerator = n;
x.denominator = 1;
}

void init(fraction x, int a, int b) {
x.numerator = a;
x.denominator = b;
}

fraction add(fraction a, fraction b) {
return a;
}

fraction sub(fraction a, fraction b) {
return a;
}

fraction mul(fraction a, fraction b) {
return a;
}

fraction div(fraction a, fraction b) {
return a;
}

void print(fraction x) {
cout << x.numerator << '/' << x.denominator;
}

}

void reduce(fraction x) {

}

int gcd(int a, int b) {
return a;
}

Main.cpp

int main() {

fraction a;
a.numerator = a.denominator = 1;
init(a,1, 2);

cout << "The fraction is: ";
print(a);
cout << endl;

return 0;
}

but I just get 0/0 every time no matter what. I think it's a pass by value/reference problem but i'm not sure how to go about fixing this.

That's the correct diagnosis. You are passing the fraction by value. The changes are made to the copy, not the original object. Change the functions to:

void init(fraction& x);
void init(fraction& x, int a);
void init(fraction& x, int a, int b);

You have the same problem with read and reduce. Change them to: