Let's say we have a class A
which has a method void foo()
. I know that I can get the pointer to foo()
by using &A::foo
, but this pointer only seems to rely on the class type, not on the instantiated object. If we have two objects a1
and a2
of type A
, how can we make a difference between the foo()
method of a1
, and the one of a2
using pointers, member function pointers, or even pointer addresses ? Basically, I want to be able to get a pointer that refers to the void foo()
method inside the a1
object, which would be different from a pointer that refers to the void foo()
method inside a2
. Thank you.
Asked
Active
Viewed 301 times
-1

baboulinet
- 7
- 1
-
1Why would two instances of a class have different member functions? – Cody Gray - on strike Jun 22 '16 at 18:16
-
2It sounds like you might be looking for function+bind but it's hard to say for sure without more detail in your question. – Mark B Jun 22 '16 at 18:21
-
Actually, they don't. Both have the same member function `void foo()`, so that we can do `a1->foo()` and `a2->foo()`. – baboulinet Jun 22 '16 at 18:22
-
1"I want to be able to get a pointer that refers to the void foo() method inside the a1 object" You must understand that there is no such thing so you cannot get it. There is only one `A::foo` method in the memory that serves all objects of type (class) `A`. That's why you **must** specify object to which you want to apply this method (for example in the form `a1->foo()` - unless that method is static. To answer question "how can we make a difference" - method get's "hidden" parameter `this` by which you know to what instance current call is made – mvidelgauz Jun 22 '16 at 19:11
-
Right, that is the point. They are the same, so why would you expect to be able to compare them as if they were different? If you already know that, I don't understand what you are asking here. – Cody Gray - on strike Jun 23 '16 at 10:06
2 Answers
0
I think you're confused here about the concept of an object (or instance of a class). An object is like a blueprint of a class. You cannot have different members / member functions for each object.
for eg.
class A
{
int result;
public:
void add(int x, int y)
{
this->result = x + y;
}
}
All the objects of Class A will have member variable result and member function add()
in it. So obj1->add()
and obj2->add()
would call the same add()
function, even though the objects itself would have different attributes from each other.
obj1->add(1,2)
would result in obj1->result
to be 3, whereas
obj2->add(1,3)
would result in obj2->result
to be 4.

Vivek Vijayan
- 337
- 5
- 19