Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complicated test to check which object instantiates a function call

Tags:

c++

I have a struct ( can be class ) and is defined in another class as shown

struct A{
somedata_A;
somespecificimplementation_A(someclass *S1);
};

class someclass{
somedata_someclass;
A a;
};

main(){
 someclass c1, *c2;
 c2 = &c1;
 c1.a.somespecificimplementation_A(c2);
}

How do I verify that c2 is indeed a reference for c1? Pardon me for putting up this example as it is obvious that c2 is reference for c1.

Update: A does not store a pointer to someclass

like image 571
Suman Vajjala Avatar asked Jul 18 '13 07:07

Suman Vajjala


3 Answers

If you don't know nothing about parent, compare member' adresses

void A::somespecificimplementation_A(someclass *S1)
{
    if (this == &(S1->a)) {
        // parent == S1
    } else {
        // parent != S1
    }
}
like image 142
Alexander Mihailov Avatar answered Oct 17 '22 18:10

Alexander Mihailov


Like that:

struct A{
  int somedata_A;
  int somespecificimplementation_A(someclass *S1){
    if ((void*) &(S1->a) == this)
    {
      std::cout << "S1 is a pointer to myself" << std::endl;
      return 1;
    }
    return 0;
  }
};
like image 26
SGrebenkin Avatar answered Oct 17 '22 19:10

SGrebenkin


Assuming struct A has a pointer to c1, you can then take a pointer to c2 and compare pointer values? Similar to what you would do with assignment operator overloads?

like image 37
user268396 Avatar answered Oct 17 '22 18:10

user268396