tags:

views:

76

answers:

4

how C++ mech works when we call object.method(), how can it call method of the class in context of the object without mixing with any other object.

and that object become "this" object in that method.

how this mapping is managed. I understand when it comes to virtual function call, you have vptr pointer and v-table to locate the function, but it is a next level activity.

+3  A: 

Under the hood, a call like object.method(1, 2); is being translated to: class::method(object, 1, 2);.

Basically, there's a "hidden" parameter for this that gets passed to the method.

Dean Harding
R Samuel Klatchko
@R Samual: Oh yeah, `object->method(1, 2)` would become `class::method(object, 1, 2)`. Thanks for the clarification :)
Dean Harding
thanks a lot. it is well answered.
vikas jain
+1  A: 

Objects are an aggregation of data members and functions that operate on those memebers/ or may do anything unrelated. So just like one can independently access a member of any other aggregation say it be structure or union or array, same way the objects could be accessed without mixing and the hidden parameter "this" to all the member functions does the charm.

Furthermore, if you consider static class functions, there is no "this" pointer with them, as they can only operate on static data members and not on the instance variables.

The vtable mechanism you talk about are a different thing used to implement polymorphism in C++ using virtual functions. In some cases, you might not actually require virtual functions unless you use polymorphism in your code.

Neeraj
"or may do anything unrelated" -> An unrelated function probably should be a free function instead of a member function.
FredOverflow
@above.. I was just making sure that being a member function doesn't necessarily requires it to operate on member elements, although i agree that is not a good design, and thats why "may"
Neeraj
+2  A: 

Basically,

class X {
  public:
    X(int i)          : i_(i) {}
    void f(int j)       {std::cout << i_+j;}
    void g(int j) const {std::cout << i_+j;}
  private:
    int i_;
};

// ...

X* px = new X(42);
px->f(1);
px->g(2);

translates roughly into

struct X {
  int i_;
};

void X_ctor(   X* const this, int i)  {this->i_ = i;}
void X_f(      X* const this, int j)  {std::cout << this->i_+j;}
void X_g(const X* const this, int j)  {std::cout << this->i_+j;}

// ...

X* px = allocate_memory(sizeof(X));
X_ctor(px,42);
X_f(px,1);
X_g(px,2);
sbi
thanks a lot for example. understood well.
vikas jain
A: 

The Function Pointer Tutorial is a great resource which you might find useful and/or interesting: http://www.newty.de/fpt/index.html

miquelramirez
it does not answer my question...
vikas jain