0

I have a line of code that looks like this:

int method(void) const;

But I'm not sure what (void) does in parameters, or what const does either. This is also supposed to be a public 'get' and I'm not sure how to approach (void) and const in classes.

1 Answers1

5

It doesn't do anything. It is a carry-over from C which indicates (in C++) that the function takes no arguments. The following signature is equivalent

int method() const;

The const following the name of the function means that (since this implies the function is a class method) the function is not allowed to change any of the member variables of the class instance.

To implement a "setter" and "getter" you typically have something like this

class Foo()
{
public:
    int GetX() const  { return x; }   // getter method
    void SetX(int x_) { x = x_; }     // setter method
private:
    int x;
}

Notice that we can declare the getter const because it does not modify the value of x, but the setter cannot be const because the whole purpose of the method is to assign a new value to x.

Dan
  • 10,532
  • 2
  • 42
  • 74
Cory Kramer
  • 98,167
  • 13
  • 130
  • 181