Reputation: 107
I'm currently learning about virtual functions, and in this particular lesson it creates an array of object pointers firstArray[5]
, and calls functions from these objects. Until now, whenever I wanted to call a function func()
from an object foo
, I would write foo.func()
. Now that I'm using virtual functions and this array, the book has switched to this method: firstArray[0]->func()
. The book doesn't do a great job at justifying this switch, could someone please explain? I see that when I try to use firstArray[0].func()
, I get this....
error: request for member 'func' in 'firstArray[0]', which is of non-class type 'sampleClass*'
.
Is it simply because I'm trying to call a function from a pointer, not an actual object? I've been learning C++ for several months now, and for whatever reason pointers still trip me up sometimes. Any clarification would help.
EDIT:
I think the part that got me mixed up is this: I can create a pointer to a base object class with base *ptr;
. Then, I can set that pointer by creating a new object from a derived class by saying ptr = new derived;
. This is where I get confused. If I were to create an int* ptr;
, and I wanted it to point to a integer I create, I couldn't say ptr = int j
. If ptr
is really just an address, why do these two examples work differently? I guess I don't understand the "new" mechanic very well either.
Upvotes: 0
Views: 87
Reputation: 49269
That doesn't have anything to do with virtual functions. If you have a pointer you need operator-> to deference and access the object it's pointing to....
You could still use the operator. (dot) to access the members/functions if you dereference first:
(*foo).func()
A pointer to an object just holds the address where the object is held in memory.
So if you have a variable which is a pointer to some type, it actually holds a number.
If you want to use the object, you need to call the object it is pointing to, which is as I said by using either operator* or operator. (dot).
Upvotes: 5