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
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.