Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
The address of virtual method is stored in the vir_table in class.When we call a virtual method, we can search the vir_table in class to get that the method which we wanted.But the normal method is not stored in the vir_table.So, when we call a normal method by an object or a pointer.How do it know the normal method address?
Posted

A non-virtual method is just like a normal global function in this regard except that it accepts an extra hidden this pointer as its first parameter. The address of a non-virtual method is a fix location in your process address space.

This may be a stupid example but the following code:
C++
struct S
{
    int i;
    void f()
    {
        printf("%d\n", i);
    }
}

S s;
s.f();

...is basically compiled to something like this:
C++
struct S
{
    int i;
}

void f(S* _this_)
{
    printf("%d\n", _this_->i);
}

S s;
f(&s);

Knowing this reveals that there is no magic happening when you issue an s.f() method call. You just call the f() "function" residing in the S namespace by specifying an S instance as its first hidden parameter (that is &s in our case).

The only difference is that the readability of the code in the first block tends to be better (in my opinion - especially when the size of codebase increases) and there you can hide method f() from outer world by making it private and f() can see the private members of S (this is some kind of documentation and prevention of abuse - converting human coder mistakes into compile errors), the same isn't true for the second code block that is much like C code. I usually start to explain the beauty of C++ for C coders through a similar example on non-virtual methods. :-)
 
Share this answer
 
v4
the normal method address gets assigned during the program compilation
 
Share this answer
 
C#
float (SomeClass::*my_memfunc_ptr)(int, char *);
// For const member functions, it's declared like this:
float (SomeClass::*my_const_memfunc_ptr)(int, char *) const;

   my_memfunc_ptr = &SomeClass::some_member_func;
 // This is the syntax for operators:
 my_memfunc_ptr = &SomeClass::operator !;


Member Function Pointers and the Fastest Possible C++ Delegates[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900