ReviseAlgo Logo

Object-Oriented Programming

this Pointer

The implicit pointer to the current object in member functions

Interview: Understanding self-reference, method chaining, and disambiguating member vs local names

this Pointer

Inside every non-static member function, this is an implicit pointer to the object on which the method was called. The compiler automatically passes it — you rarely write it explicitly, but understanding it demystifies member function calls, method chaining, and self-reference patterns.

Type of this

In a non-const member function, this has type ClassName* const — a const pointer to a mutable object. You can modify the object's members but cannot reassign this itself. In a const member function, this is const ClassName* const — neither the pointer nor the object can be modified.

Method Chaining

Returning *this by reference enables fluent interfaces and method chaining: builder.setName("x").setAge(5).build(). The Builder pattern and stream operators (cout << a << b) both use this technique.

Disambiguating Names

When a parameter or local variable has the same name as a member variable, this->name explicitly refers to the member. Though better practice is to use a naming convention (e.g., m_ prefix) to avoid ambiguity entirely.

Interview Corner

Q: Can you call a method on a null pointer?

A: Calling a method on a null pointer is undefined behavior. However, for non-virtual methods that don't access this (don't access members), some implementations happen to work — but this is not portable and should never be relied upon. Virtual method calls on null pointers always crash due to vtable lookup requiring a valid object.

Q: What is enable_shared_from_this and when do you need it?

A: When a class managed by shared_ptr needs to hand out more shared_ptrs to itself from within a member function, it cannot use shared_ptr<T>(this) — that creates a second control block causing double-free. Inheriting from std::enable_shared_from_this<T> and calling shared_from_this() safely returns a shared_ptr sharing the existing control block.

Common Pitfalls

  • Using this in constructor initializer list incorrectly: this is valid in the constructor body and initializer list, but the object isn't fully constructed — don't call virtual functions or pass this to external functions in constructors.
  • Creating shared_ptr from this directly: Creates a separate control block — double-free on destruction. Use enable_shared_from_this.

Best Practices

  • Use member name conventions (e.g., m_name or name_) to avoid needing explicit this-> disambiguation.
  • Return *this by reference from mutating methods to support fluent interfaces.