-2

I remembered, from university, that const method can not changes fields. I am returning to C++ now, and I have written simple program.

#include "stdafx.h"

#include <iostream>

using namespace std;

class Box
{
    int a;
    int b;
    int square;

public:
    Box(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    const void showSquare(void) const
    {
        cout << this->a * this->b << endl;
    }

    const void setDim(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Box b(2, 4);
    b.showSquare();
    b.setDim(2, 5);
    b.showSquare();
    int a;
    cin >> a;
    return 0;
}

In my case const method can change fields of class? How is it possible?

Than you in advance.

J. Doe
  • 77
  • 1
  • 1
  • 8
  • 4
    `const void setDim(int a, int b)` isn't a proper signature for a const method. That would be `void setDim(int a, int b) const`. – Bo Persson Jan 21 '17 at 22:51
  • `showSquare()` uses `const` to indicate not changing the "fields". `setDim()` uses `const` to show that the return value of the function doesn't change (which is meaningless, but permitted, when returning `void`) but that is something unrelated to whether the function changes "fields". – Peter Jan 22 '17 at 00:55

2 Answers2

1

setDim in your question is not a const method. The method's return type is const void. Since the method returns void, the const really makes no difference.

If you want the method to behave like a const method (a method not supposed to change the state of the object), move the const to the end of the signature

void setDim(int a, int b) const 
    {
       // do read only operations on the object members.
    }

How many and which are the uses of “const” in C++? would be a good refresher.

Community
  • 1
  • 1
HappyTown
  • 6,036
  • 8
  • 38
  • 51
0

const void is the return value which is const not the const this pointer which cannot change the member data:

class A
{
    public:
        void show()const // this pointer here is constant so this method cannot change any member data or Call any other non-const member
        {
            a = 0; // compile time-error 

            setValue(7); // also compile time error: `error C2662: 'setValue' : cannot convert 'this' pointer from 'const class A' to 'class A &'`
            cout << a << endl;
        }

        const void setValue(const int x)
        {
            a = x; // ok
        }

        private:
            int a;
};
Raindrop7
  • 3,889
  • 3
  • 16
  • 27