Edit: sorry about the stupid title; by “pointer object” I think I mean dereferenced object pointer (if that’s any clarification).
I’m new to C++, and I’ve been trying to get used to its idiosyncrasies (coming from Java).
I know it’s not usually necessary, but I wanted to try passing an object by its pointer. It works, of course, but I was expecting this to work too:
void test(Dog * d) {
*d.bark();
}
And it doesn’t. Why is this? I found out that I can do the following:
void test(Dog * d) {
Dog dawg = *d;
dawg.bark();
}
and it works flawlessly. It seems so redundant to me.
Any clarification would be appreciated. Thanks!
You have to use the
->operator on pointers. The.operator is for non-pointer objects.In your first code snippet, try
d->bark();. Should work fine!EDIT: Other answers suggest
(*d).bark();. That will work as well; the(*d)dereferences the pointer (ie. turns it into a normal object) which is why the.operator works. To use the original pointer, simplyd, you must use the->operator as I described.Hope this helps!