I couldn't understand the reason for not allowing modifiers such as const
or volatile
to nonmembers functions.
Following is the example code I tired
class A
{
private:
int var;
public:
int func();
};
int A::func()
{
// Some calculation on using var
int temp = var + 10;
return temp;
}
void func2( const A& tempObj ) const;
void func2( const A& tempObj )
{
std::cout << "temp obj called : " << tempObj.func() << std::endl;
}
int main()
{
A aobj;
aobj.func();
func2( aobj );
return 0;
}
which throws an compiler error error C2270: 'func2' : modifiers not allowed on nonmember functions
for void func2( const A& tempObj ) const;
I also get another error error C2662: 'A::func' : cannot convert 'this' pointer from 'const A' to 'A &'
for tempObj.func()
in func2
here I was assuming that the member function func
will be called without any errors.
const
modifier states that a member function won't modify data members of the object the function belongs to.
It's like an assurance that calling that function on an object aobj
won't modify the internal state of that object. So, assuming that aobj
is declared const
too, you will still be able to invoke that function on it; on the contrary, you would not be able to invoke non const
function members.
If a function is not member of a class, it makes no sense to apply const
modifier. On another language, it could have meant that the function wasn't able to modify global variables, maybe; but that language is not C++.
Imagine that there is a hidden parameter on each non-static member function:
int A::func(A* this) {...}
If you declare a member function const or volatile, that is added to that hidden parameter, pretty much like the following:
int A::func(const A* this) {...}
Some languages like python make the instance parameter on the member functions explicit, so there you write def func(self):
inside a class definition to declare non-static functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With