What does 'this' really mean?
In Java I can do this.method(); on any method of my current class, or any super class as long as the method is not private. From toying around a bit in C++, it seems I can't do this->methodOfSuper(); Is that a correct understanding? STH
Steven T. Hatton wrote:
In Java I can do this.method(); on any method of my current class, or any super class as long as the method is not private. From toying around a bit in C++, it seems I can't do this->methodOfSuper(); Is that a correct understanding?
No. If A is a superclass of B and f() is a public or protected method of A, then any nonstatic method of B can use this->f() to access A::f(), provided there is no B::f(). It doesn't matter if f() is virtual or static or if the inheritance is public, protected or private. If B::f() exists, then this->A::f() will access A::f(). In practice, you can use f() instead of this->f() in B, which is usually easier. I mainly use this so that I can match nonconst object field names with parameter names, as in class A { public: A( int x ){ this->x = x; } private: int x; }; Even there, I might use A( int x ): x( x ){} instead, though that's not needed unles x is const. -- JDL
participants (2)
-
John Lamb
-
Steven T. Hatton