Const Correctness Part 6

by Darren Collins
Sunday, 4 April 2004

This will be my last article on const correctness for a while. I hope I haven't bored anyone yet - it's a very important aspect of writing robust, maintainable code.

Last week's article discussed declaring const functions in your classes. Const functions are the only member functions that can be called by const objects of your class. This week I'll show you how you can use overloaded functions to determine whether the invoking object is const or not.

Consider the class below:

class A
{
  public:
    A(int i = 0) : _val(i) {}
    void f() { cout << "A::f()" << endl; }
    
    int _val;
};

We can call f() only for non-const objects, since we declared it as a non-const member function.

We can overload f() to allow const objects to invoke it by declaring a second public member function like this:

void f() const { cout << "A::f() const" << endl; }

We can write a program to show how the two different member functions are invoked by const and non-const objects:

#include <iostream>

class A
{
  public:
    A(int i = 0) : _val(i) {}
    void f() { cout << "A::f()" << endl; }
    void f() const { cout << "A::f() const" << endl; }
    
    int _val;
};

int main()
{
  A a(5);
  cout << "Invoking a.f() calls ";
  a.f();
  
  A const b(2);
  cout << "Invoking b.f() calls ";
  b.f();
}

The output will be:

Invoking a.f() calls A::f()
Invoking b.f() calls A::f() const

Now try commenting out the non-const member function:

// void f() { cout << "A::f()" << endl; }

Now the program produces this output:

Invoking a.f() calls A::f() const
Invoking b.f() calls A::f() const

You can see that if a non-const member function doesn't exist, a non-const object will happily invoke the const one.

Commenting out the const member function results in a compile-time error. Try it, so you can see what error message your compiler produces when you try to invoke a non-const member function on a const object.

Summary

  1. You can define const and non-const versions of the same member function, and the compiler decides which one to call by examining the 'constness' of the invoking object.
  2. If only a const version of the member function exists, the compiler will call it when a non-const object invokes that function.
  3. If only a non-const version of the member function exists, the compiler will generate an error if a const object tries to invoke that function.

 


Related Articles
Index
- Links - C/C++
- Code Layout Styles
- Const Correctness Part 1
- Const Correctness Part 2
- Const Correctness Part 3
- Const Correctness Part 4
- Const Correctness Part 5
- Const Correctness Part 6

This site Copyright 1999-2005 Darren Collins.