constant function is called by non constant object. Why?

765 Views Asked by At

I am a newbie in c++ and facing a problem with constant objects. I have declared a constant member function named function (and as I have learned that a constant function can only be called by a constant object) but here a regular object calls a constant object. Please explain why this is happening. Code is here

myClass.h

#ifndef MYCLASS_H
#define MYCLASS_H

class myClass
{
    public:
        void function() const;  
};

#endif

myClass.cpp

#include "myClass.h"
#include<iostream>
using namespace std;

void myClass::function() const{
    cout<<"this is a constant object";
}

main.cpp

#include <iostream>
using namespace std;
#include "myClass.h"

int main() {
    myClass obj;
    obj.function();

    return 0;
}

Please help me out. Thanks

2

There are 2 best solutions below

0
On

as I have learned that a constant function can only be called by a constant object

No!

It's the other way around:

  • a const member function promises to only read the object, so it can be called even when changes are not possible;
  • a non const member function (let's say called "MF") can read and modify the object, so:

    • it cannot be called either from a const member function (let's say called "CMF"): functions called by a function (here "CMF") shouldn't break the promise made, and "MF" would risk breaking the promise;
    • it cannot be called on a const object, which is constant when its construction has finished and until destruction (during construction the object declared const is not constant yet, as the constructor needs to set it up).

So a const qualified member function can be applied to any object; the limit is on what these const member functions can call.

0
On

That is the way C++ works. It is fine to call a const member function on a non-const object, because const correctness cannot be broken that way. What is not OK is to call a non-const member function on a const object.

Note that if you had a non-const overload of function(), that one would be called.