Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constant function is called by non constant object. Why?

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

like image 253
Ritik Saxena Avatar asked Apr 30 '26 16:04

Ritik Saxena


1 Answers

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.

like image 128
juanchopanza Avatar answered May 03 '26 08:05

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!