-1

Here's an example to explain my question:

//myfile.h
class thing
{
public:
    void doSomething();
private:
    Book *text;
};

Now, inside the doSomething method, how do I call the Book object's method read()? Read() is nonstatic. For this example lets say I made a thing object called obj, which called doSomething().

Would the proper call be: obj->read(), or this.obj->read()

harper
  • 13,345
  • 8
  • 56
  • 105
user1553248
  • 1,184
  • 2
  • 19
  • 33
  • 3
    The answer is completely unrelated to pointers. It’s the same behaviour for *all* members. Furthermore, evaluate whether a pointer is really what you want. In most situations, pointers have no place in modern C++. – Konrad Rudolph Aug 03 '12 at 17:01
  • 1
    why not just test? text->read() – RiaD Aug 03 '12 at 17:02
  • 5
    @RiaD The testing approach fails miserably with C++ due to the pervasive existence of undefined behaviour. – Konrad Rudolph Aug 03 '12 at 17:03
  • Not to add to the confusion, but you could use the dereference operator `*` and do something like this `(*obj).read()` but the dereference arrow does that for you. In general, make sure to check your pointer `!= NULL` – RageD Aug 03 '12 at 17:04
  • 2
    You **really** need to start reading a [C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Praetorian Aug 03 '12 at 17:12

2 Answers2

4

The proper call would be text->read(). You can also usethis->text->read().

In your example, there is no need to use this. Also note that this is a pointer, so this.next->read() would not even compile.

Edit if you "made a thing object called obj, which called doSomething()" then there does not even have to be a this, depending on where you instantiate the thing. If the thing is not a data member of another object, then you simple need:

thing obj;
....
obj.doSomething();

In any case, you cannot call obj.read() since thing has no read() method.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

It would just be:

text->read()
James M
  • 18,506
  • 3
  • 48
  • 56