C++ type qualifier problem

c++qualifierstypes

As part of my Computer Software Development degree, one of my labs consists of creating a calculator class template and a fraction class.

The problem is with my fraction class. My task is now to overload the plus operator to allow two fractions to be added together.

Fraction.cpp:

#include "Fraction.h"

const Fraction Fraction::operator+ (const Fraction &rhs) const
{
    return Fraction(_num * rhs.GetDen() + (rhs.GetNum() * _den), _den * rhs.GetDen());
}

Fraction.h

#pragma once

class Fraction
{
    public:
        Fraction(const int &num, const int &den) : _num(num), _den(den) {}
        ~Fraction(void) {}
        const int GetNum(void) { return _num; }
        const int GetDen(void) { return _den; }
        const Fraction operator+ (const Fraction &rhs) const;

    private:
        const int _num, _den;
};

Visual Studio complains that my fraction accessors cannot 'convert this pointer from const fraction to fraction &'. I'm completely baffled.

Best Solution

You need to qualify your accessors as const too:

int GetNum(void) const { return _num; }

BTW, qualifying the return type as const int does not really make sense, it will be an int anyway. Your compiler should emit a warning.