thG
thG

Reputation: 27

Calling a private function using a public funtion

In my assignment, i am required to call a private function (simplify) from a public function ( set(int,int) ). When i try to compile, i get an error that says redefinition of set . Im not sure what im doing wrong, or what the error means. any help is very much appreciated. Here is what i have:

//Fraction.h

struct Fraction{
    private:
            int numerator;
            int denonminator;
            void simplify();

    public:
            void set(int n, int d){void simplify();};
            void display() const;
};

//Fraction.cpp

#include <iostream>
using namespace std;
#include "Fraction.h"

void Fraction::set(int n, int d){
    numerator = n;
    denonminator = d;
    simplify();
}

void Fraction::simplify(){
    int i;
    for (i = denonminator * numerator;  i > 1; i--){
            if( denonminator % i == 0 && numerator % i == 0){
                    numerator = numerator/i;
                    denonminator = denonminator/i;
                }
        }
}

void Fraction::display () const{
        cout << numerator << " / " << denonminator;
}

Upvotes: 0

Views: 110

Answers (3)

Barry
Barry

Reputation: 302718

You defined set twice:

struct Fraction{
    void set(int n, int d){void simplify();}; // <== #1
};

And:

void Fraction::set(int n, int d) { // <== #2
    numerator = n;
    denonminator = d;
    simplify();
}

The first definition doesn't do what you want anyway - it's not calling simplify, it's declaring a local function named simplify that takes no arguments and returns void - which has nothing to do with Fraction::simplify. So just replace it with:

void set(int n, int d);

Upvotes: 2

Srinath Mandava
Srinath Mandava

Reputation: 3462

You are defining set twice.. Better declare it once

struct Fraction{
    private:
            int numerator;
            int denonminator;
            void simplify();

    public:
           // Dont use this-- void set(int n, int d){void simplify();}; //Defined here once
            void set(int n, int d); //Just declare it
            void display() const;
};

//Fraction.cpp

#include <iostream>
using namespace std;
#include "Fraction.h"

void Fraction::set(int n, int d){//Defined it again
    numerator = n;
    denonminator = d;
    simplify();
}

void Fraction::simplify(){
    int i;
    for (i = denonminator * numerator;  i > 1; i--){
            if( denonminator % i == 0 && numerator % i == 0){
                    numerator = numerator/i;
                    denonminator = denonminator/i;
                }
        }
}

Upvotes: 1

danielschemmel
danielschemmel

Reputation: 11116

Fraction::set is implemented twice: You already implemented it in the header - and implement it again in the .cpp file.

You have to decide on one implementation.

Looking at what both implementations do, you should probably change the header to read

//...
void set(int n, int d);
//...

Upvotes: 2

Related Questions