Reputation: 3315
why I can call non const method from ref member inside const method? I am expected to get compile error like in case if m_a were not reference type. run on http://cpp.sh/
// Example program
#include <iostream>
class A
{
public:
void nonConstMethodOfA()
{
std::cout << "nonConstMethodOfA is called" << "!\n";
}
};
class B
{
public:
B(A& a)
: m_a(a)
{
constMethodOfB();
}
private:
A& m_a;
void constMethodOfB() const
{
m_a.nonConstMethodOfA();
}
};
int main()
{
A varA;
B varB(varA);
}
Upvotes: 2
Views: 84
Reputation: 10880
Const member function means your this
will point to a const object, thus this->fn()
can only be called if fn()
is const. It doesn't lock the type, nor any similar-typed input parameters or globals. You can, however, specify those as const as well if you wish.
Upvotes: 1
Reputation: 69864
const A &
means "a reference to a const A"
A &
means "a reference to a mutable A"
A reference cannot be reassigned, so A &
also implicitly means "a const reference to a mutable A".
Upvotes: 2