1

I have a function in a class with const key word:

bool Machiavelli::IsStraight(std::vector<Card>& cards) const{}

Machiavelli is class that have other classes inside, like Card and Table:

class Table{
    private:
            std::map<int, std::vector<Card> > table;
    ....
};

The vector in the function is a vector of table. The function check if the cards assemble a straight.

Now, in the function I change the value of a data of Card function:

cards[i].SetIntValue(14);

where SetIntValue is a function in Card class.

Reading some question, I read:

const after a function declaration means that the function is not allowed to change any class members (except ones that are marked mutable).

The function doesn't know that the argument is in Machiavelli, so I can change a class member: table. Where my reasoning fails?

linofex
  • 340
  • 1
  • 2
  • 17

3 Answers3

7

A method declared as const cannot modify members, as long as it is trying to modify them through the implicit this pointer of the method.

Consider the following class:

struct foo
{
    void bar(int *i) const {
        *i = 0;
        _m = 0;
    }

    int j;
    int _m;
};

Suppose we call

foo f;
f.bar(&f.j);

Then the line

        *i = 0;

is fine. Even though it is actually modifying j, it is not doing it through this. However,

        _m = 0;

really means

        this->_m = 0;

and so it won't build - the const of the function means it cannot modify it.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
2

Because your const function is not changing a class member.

It is changing the vector that's passed as a parameter to the function.

The fact that whatever is calling the function is passing a vector that happens to be a member of the same class is a completely different issue.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
1

const after a function declaration means that the function is not allowed to change any class members (except ones that are marked mutable).

This is not entirely right. A small but important correction is needed.

const after a function declaration means that the function is not allowed to change any data via its class member variables (except via ones that are marked mutable).

Note that a variable is not data, it's a name for data.

Since cards is not a class member variable, it is possible to change data via cards, even if it's the same data that sits in the member variable table.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243