Greetings

I want to know what is the difference between passing an agrument by reference as a constant and making the function itself a constant. A constant argument means that the function cannot modify it anyway and any attempt to do so, will report an error from the compiler what means a garantee that the argument cannot be modified within the function. The constant function means also that the function will not modify any of its data. So what is the difference between making the agrument constant and making the function itself constant?

Recommended Answers

All 3 Replies

First of all, only non-static member functions can be declared as const. The const-ness applies to the object on which the member function is called, that is, the object and thus all the data members it contains. Here is an example:

class Foo {
  public:
    int bar;

    void member_func() const;
};

void free_func(const Foo& f);

void Foo::member_func() const {
  bar = 42;   // ERROR: data-member 'bar' cannot be modified, it is part of a const object.
};

void free_func(const Foo& f) {
  f.bar = 42; // ERROR: data-member 'bar' cannot be modified, it is part of a const object.
};

int main() {
  Foo f;
  f.member_func();  // calling 'member_func' on the object 'f'
  free_func(f);     // calling 'free_func' on the object 'f'
};

So what is the difference between making the agrument constant and making the function itself constant?

As you see from the above example, nothing is different. Qualifying the member function as const is just the way to tell that the first hidden argument to the function (which is the object on which the member function is called) must be treated as const within the function.

You ask "So what is the difference between making the agrument constant and making the function itself constant?"

You can imagine having a const member function of an object. This means that whenever you call that function the object itself is not modified. The data inside the object is guaranteed to remain unchanged.

But a constant object can change parameters sent to it, or return values.

A washing machine could be considered a constant object with constant functions. You hand it dirty clothes and it changes them into clean clothes. But the washing machine itself is not changed. You use the const object to do things for you. Making a function consts enforces that rule.

A cow eating grass on the other hand both changes itself when eating the grass and the grass (into milk). A cow is not a const object!

The data inside the object is guaranteed to remain unchanged.

Unless it's mutable, or the function does something tricky to bypass constness. Rule #1 of C++ is that there are no guarantees. Stupid or malicious code can get around any language restriction. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.