Importance of Being Const
Lecture Referred
--- Notes Start Here --- 1. Taken from google style guide -
cpp
class T{
returnValue FunctionName(args) CV-qualifiers; // CV-qualifiers: const, volatile, const volatile
};
- How the compiler sees them?
- Step 1: Original member function
```cpp
int Foo::GetValue() const
{
return mValue;
}
```
- Step 2: `this` pointer added as first hidden argument
```cpp
int Foo::GetValue(Foo const* const this)
{
return mValue;
}
```
- Step 3: CV qualifiers on `this` pointer
```cpp
// const member function → this is pointer to const
int Foo::GetValue(Foo const* const this)
{
return this->mValue;
}
```
- Step 4: Non-const member function for comparison
```cpp
// non-const member function → this is pointer to non-const
int Foo::GetValue(Foo* const this)
{
return this->mValue;
}
```
- Step 5: Function invocation translated
```cpp
// What you write:
Foo f;
auto v = f.GetValue();
// How compiler sees it:
Foo f;
auto v = GetValue(&f);
```
- Step 6: Name mangling (implementation-defined)
```cpp
// Compiler generates mangled name
int __ZNK3Foo8GetValueEv(Foo const* const this)
{
return this->mValue;
}
// Function call becomes:
Foo f;
auto v = __ZNK3Foo8GetValueEv(&f);
```
- Key insight: const member functions take `Foo const*`, non-const take `Foo*`
- This is why you can't call non-const methods on const objects
- <p align="center">