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
No!
It's the other way around:
a non const member function (let's say called "MF") can read and modify the object, so:
So a const qualified member function can be applied to any object; the limit is on what these const member functions can call.