const and non-const method override

I personally do not use const and non-const method overload. Since it is sometimes unclear for me which method is called. This is a simple example (much easy to understand), but there are more complicated cases.

Most of the case I want to use an overload for the const or non const method is an accessor. So, I coin method names as get_*() and peek_*(). I can get data without changing the state of the object by get_* methods, so this is a const method. But if I am peeking inside of the object and may change the state -- non const method with name peek_*().

The class B's has only const methods derived from class A, however, which still can calls non-const method in A. I think this is not intuitive for me, since a const method calls a non-const method of the internal methods when const and non-const methods are overloaded.

If I think carefully, I understand this is correct, but I need to think about it, so I do not use it. I will just change the method name, then I will be never confused and not need to think about it.

The reference case calls non-const method since a reference is virtually a pointer. So the const-ness of the pointer is guaranteed by the call_for_ref() const. However, it does not say the object const-ness. Therefore, call_for_ref() const calls non-const method.

My colleague, a language master, Ali showed me a similar example. Thanks! 2008-07-17

// Example const and non-const overload.
#include <iostream>

class ClassA
{
public:
  void print() {
    std::cout << "print()" << std::endl;
  }
  void print() const {
    std::cout << "print() const" << std::endl;
  }
};

class ClassB
{
public:
  ClassB(ClassA & aref) : m_ref(aref){}
  void call_for_ref() const { m_ref.print(); }
  void call_for_obj() const { m_obj.print(); }
private:
  ClassA & m_ref;
  ClassA   m_obj;
};

int main()
{
  ClassA aobj;
  ClassB bobj(aobj);

  // This calls print() or print() const?
  bobj.call_for_ref();
  // This calls print() or print() const?
  bobj.call_for_obj();

  return 0;
}

Copyright (C) 2008 YAMAUCHI Hitoshi
Most recent update : :