user14611431
user14611431

Reputation:

Using functions while overloading an operator

I'm currently working on a game to brush up my C++ skills and I'm trying to use more advanced concepts in order to learn more about the language itself.

I'm creating a deck of cards using an enum to store the values and would like to overload the << operator to have a clean way to print everything.

//Card.h
private:
    Value value;
    Suit suit;

enum Value {
        TWO = 2, THREE...
    };
enum Suit {
        DIAMONDS, SPADES, CLUBS, HEARTS
    };
Card(Value value, Suit suit);
friend std::ostream& operator<<(std::ostream& output, const Card& card);

In order to maintain readability, I have get functions for values and suits using switch/case.

std::string Card::getSuit() {
    int c = suit;
    std::string strSuit;
    switch(c) {
        case 0:
            strSuit = "Diamonds";
            break;
        case 1:
            strSuit = "Spades";
            break;
        case 2:
            strSuit = "Clubs";
            break;
        case 3:
            strSuit = "Hearts";
            break;
        default:
            ;
    }
    return strSuit;
}

(getValue is similar but omitted to reduce question length)

My idea for the function to overload the operator is:

std::ostream& operator<<(std::ostream& output, const Card& card) {
    std::string v = card.getValue();
    std::string s = card.getSuit();
    output << v << " of " << s << std::endl;
    return output;
}

however the get functions do not work because of a conflict with the const (which I do not fully understand).

How can I overload this operator cleanly, without having to duplicate the switch/case statements?

Upvotes: 0

Views: 77

Answers (1)

Morgan V
Morgan V

Reputation: 71

'const' on the C++ member function basically means that it's 'read-only',the function is not allowed to alter/modify any member variables of the class-instance (this) - and to to call other functions, those must also be 'const', example, this would be illegal, and not compile:

int SomeClass::getSomeValue() const
{
    this->some_example_counter++; // not allowed to modify member here
    return this->some_member_value;
}

Now it's possible to define 'some_example_counter' as 'mutable', and then it will be allowed to be modified/altered from a 'const' member function.

class SomeClass {
   ...
   mutable int some_example_counter;
}

There are some few rare use-cases where 'mutable' will make sense, like for example when a 'mutex' may be needed, otherwise personally I avoid using 'mutable'.

In your code:

std::ostream& operator<<(std::ostream& output, const Card& card)

The second parameter 'const Card& card' - you can only call memeber function of Card class that are 'const' (read-only) I think it would in any case make sense to have both Card::getValue() and Card::getSuit() as 'const' - as they naturally don't alter/modify any member variable of Card.

Upvotes: 2

Related Questions