In C++, which of the following are legal ways to access a data member x from inside a member function using the this pointer? Assume x is a non-static data member of the current class.

Difficulty: Easy

Correct Answer: this->x

Explanation:


Introduction:
The keyword this is a pointer to the current object inside non-static member functions. This question checks knowledge of pointer syntax versus direct-member access syntax when referencing a field named x through this.


Given Data / Assumptions:

  • Inside a non-static member function.
  • this has type T for class T.
  • x is a valid non-static data member of T.


Concept / Approach:
Because this is a pointer, the correct operator to access a member is the arrow operator: this->x. The dot operator requires an object (not a pointer). Parentheses are required if you explicitly dereference this and then use dot: (*this).x is valid, but the option given as *this.x is parsed incorrectly as *(this.x) and is invalid.


Step-by-Step Solution:
1) Recognize that this is a pointer to the current object.2) Use pointer-to-member access: this->x.3) Alternative (not listed): (*this).x also works because *this yields an lvalue object.4) Any form missing parentheses or misusing dot/arrow is ill-formed.


Verification / Alternative check:
Compile a snippet with both this->x and (*this).x; both compile. Try this.x or *this.x and observe compilation errors due to incorrect parsing.


Why Other Options Are Wrong:
this.x: dot requires an object, not a pointer.*this.x: parsed as *(this.x), accessing a member x of pointer this (nonsense).*this-x: arithmetic on pointers mixing dereference and subtraction; unrelated and invalid for member access.


Common Pitfalls:
Forgetting parentheses around *this when using dot, leading to precedence errors. Prefer this->x for clarity.


Final Answer:
this->x

More Questions from OOPS Concepts

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion