In the class member functions, we have seen using data members directly. One must ask how does C++ know whose object’s data members to access as we have not specified any object name? For example,
class Int
{
private:
int m_value{};
public:
Int() = default;
Int(int value)
: m_value{value}
{
}
void print()
{
std::cout << "Int(" << m_value << ")\n";
}
};
int main()
{
Int i{1};
i.print();
return 0;
}How i.print() knows to use i’s data member m_value? This where this comes into the picture.
this
this is a pointer that points to the implicit object (on which member function is invoked). Behind the curtains, C++ uses this pointer to access the object’s data members. When the program is compiled, any access to the data member is rewritten by prefixing the access with this pointer. We can also access data member using this pointer:
void print()
{
std::cout << "Int(" << this->m_value << ")\n";
}And it works.
Note
I have discussed how to access members from object pointer here.
How this is set?
For us, we are just calling i.print(), but for C++ after the compilation, it is rewritten as:
Int::print(&i);So, print is accepting address of the implicit is object. For this to work, compiler also rewrites member function definition something like below (depends on the compiler implementation):
static void print(Int* const this)
{
std::cout << "Int(" << this->m_value << ")\n";
}print is accepting Int const pointer so that pointer can’t point something else.
Note
staticbecause it does not belong to any class object, but rather resides in the class scope. This is called static member function.
this with const objects
For non-const member functions, this pointer is a const pointer to non-const object as argument and for const member functions, this is a const pointer to const object. So, when non-const member function is invoked on const object and this which is const pointer to const object, compiler can’t implicitly convert pointer to const to pointer to non-const. So, doing this fails.
For example:
void print() const
{
std::cout << "Int(" << this->m_value << ")\n";
}would be rewritten as:
static void print(const Int* const this)
{
std::cout << "Int(" << this->m_value << ")\n";
}so,
const Int i{1};
Int::print(&i); // worksbut for,
void print()
{
std::cout << "Int(" << this->m_value << ")\n";
} static void print(Int* const this)
{
std::cout << "Int(" << this->m_value << ")\n";
}following would not work
const Int i{1};
Int::print(&i); // failsAs we are trying to pass const pointer to print which accept pointer to non-const (we could pass pointer to non-const to parameter of type pointer to const).