OOP: ACCESS SPECIFIERS
`this` Pointer
Inside a non-static member function, this points to the object that called the function.
Simple idea:
this = address of the current object
Example
#include <iostream>
class Counter {
private:
int value = 0;
public:
void increment() {
this->value++;
}
int getValue() const {
return this->value;
}
};
int main() {
Counter counter;
counter.increment();
std::cout << counter.getValue() << '\n';
}
You usually do not need to write this-> unless it improves clarity or solves a name conflict.
Resolving Name Shadowing
Sometimes a parameter has the same name as a data member.
class Employee {
private:
int id = 0;
public:
void setId(int id) {
this->id = id;
}
};
Without this->, id = id; would assign the parameter to itself.
Returning *this
this is a pointer.
*this means the current object.
Returning *this allows method chaining.
#include <iostream>
class Box {
private:
int length = 0;
int width = 0;
public:
Box& setLength(int value) {
length = value;
return *this;
}
Box& setWidth(int value) {
width = value;
return *this;
}
void display() const {
std::cout << length << " x " << width << '\n';
}
};
int main() {
Box box;
box.setLength(10).setWidth(5);
box.display();
}
Important Guides
- Only non-static member functions have
this. - Friend functions do not have
thisbecause they are not member functions. - You do not declare
this; the compiler provides it. - In a normal member function,
thisbehaves like a constant pointer to the current object.
Viva Answer
this is an implicit pointer available inside non-static member functions. It points to the current object. It is useful for resolving name conflicts and returning *this for method chaining. Friend functions do not have this because they are not members.
Quick Check
- What does
thispoint to? - Does a friend function have
this? - Why use
this->id = id? - What does returning
*thisallow?