Solved

Function call problem

Posted on 2002-04-06
5
251 Views
Last Modified: 2010-04-02
I have a program where there is a class and i call a function of the class in main:
#include <iostream>
using namespace std;

class Class {
     virtual void fun(char* ch) { cout << "Class::fun " <<ch<< endl; }
};

typedef void (*Fun)(char*);

int main() {
     Class objClass;

     cout << "Address of virtual pointer " << (int*)(&objClass+0) << endl;
     cout << "Value at virtual pointer i.e. Address of virtual table "
           << (int*)*(int*)(&objClass+0) << endl;
     cout << "Value at first entry of virtual table "
           << (int*)*(int*)*(int*)(&objClass+0) << endl;

     cout << endl << "Executing virtual function" << endl << endl;
     Fun pFun = (Fun)*(int*)*(int*)(&objClass+0);
     pFun("hello");
     return 0;
}

If the function fun of class Class had no argument then their is no error, but since there is an argument(char* type) and I am sending the parameter hello to fun. There is a run time error of chkesp.c. Please help me.

0
Comment
Question by:manas_ghosal
5 Comments
 
LVL 2

Expert Comment

by:udil
ID: 6922662
I'm not sure what you're trying to do.
However, every method (function of the class) has an implicit first parameter which is a pointer to the self object (reserved keyword: this).
The only class member functions that do not have such a parameter are static member functions.

udil
0
 
LVL 2

Expert Comment

by:udil
ID: 6922689
example:

#include <stdio.h>

typedef void (*Fun)(int);

class CMyClass
{
  public:
    typedef void (CMyClass::*pvf) (int);

    CMyClass (void)  {}
    void exec(void);

    void func_1(int i);
     static void func_2(int i);

    pvf pFuncPtr;     // Function called to execute
};

void CMyClass::func_1(int i)
{
     printf("func_1 called with %d\n", i);
}

void CMyClass::func_2(int i)
{
     printf("func_2 called with %d\n", i);
}

void CMyClass::exec(void)
{
     printf("exec called\n");
     (this->*pFuncPtr)(4);
}

int main (void)
{
    CMyClass cObj;
     cObj.pFuncPtr = CMyClass::func_1;
     cObj.exec();

     Fun pFun = CMyClass::func_2;
     pFun(5);

    return 0;
}
0
 
LVL 49

Accepted Solution

by:
DanRollins earned 100 total points
ID: 6923201
Teaching to fish:

1) Change your code to look like this:

class Class {
public:
    virtual void fun(char* ch) { cout << "Class::fun " <<ch<< " this:" << this << endl; }
};
typedef void (*Fun)(char*);
char sHello[]= "hello";
Class objClass;
int main() {
    objClass.fun( sHello );
    pFun( sHello );
    cout << "Done" << endl;
    return 0;
}

2) Place a breakpoint on    
    objClass.fun("hello");
3) run the program.  At breakpoiunt use command View/Debug Windows/Disassembly.  

This will show you what is different between the call via the vtable and the 'normal' call to the virtual member fn.  For clarity, I turned off code optimzation on an otherwise 'Release' build.  As you can see...

29:       objClass.fun( sHello );
68 B0 70 42 00       push        offset sHello (004270b0)
B9 34 B3 42 00       mov         ecx,offset objClass (0042b334)
E8 B4 00 00 00       call        Class::fun (00401220)
30:
31:       pFun( sHello );
68 B0 70 42 00       push        offset sHello (004270b0)
FF 55 FC             call        dword ptr [pFun]
83 C4 04             add         esp,4


... there are only two differences:  The 'normal' call sets ECX to point ot the object (it is a requirement of the 'thiscall' calling convention) and the 'indirect' call does not do that, but DOES pop the stack (add esp,4) to discard the pointer to sHello that it pushed (this is a requirement of the 'cdecl' calling convention).

This is fascination to me ),maybe I don't get out enough)  So I tried some variations.  If the pointer is declared like this:

   typedef void (__stdcall *Fun)(char*);

then the compiler will generate:
    31:       pFun( sHello );
    68 B0 70 42 00       push        offset sHello (004270b0)
    FF 55 FC             call        dword ptr [pFun]
    32:

because it has been instructed NOT to cleanup the stack after the call.  That is what we want because objClass.Fun already cleans up the stack.  However, ECX will contain a random value going into the function.  That will result in a problem if objClass.Fun calls any other members of its class (it won't be able to find its variables or vtable).  You can only correct that by setting ECX manually:

    __asm mov ECX, offset objClass
    pFun( sHello );

Isn't learning new stuff fun?

-- Dan
0
 
LVL 11

Expert Comment

by:griessh
ID: 6957241
Good job, Dan!!!!!!

====================

Dear manas_ghosal

I think you forgot this question. I will ask Community Support to close it unless you finalize it within 7 days. You can always request to keep this question open. But remember, experts can only help you if you provide feedback to their questions.
Unless there is objection or further activity,  I will suggest to accept

     "DanRollins"

comment(s) as an answer.

If you think your question was not answered at all, you can post a request in Community support (please include this link) to refund your points. The link to the Community Support area is: http://www.experts-exchange.com/commspt/

=========================================================
You have 18 open questions out of 23 that need your attention! Please take
some time and accept an answer if an expert was able to help you or
provide feedback if needed.
==========================================================

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
======
Werner
0
 
LVL 1

Expert Comment

by:Moondancer
ID: 6979256
You still have questions open dating back to the year 2000.  ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if they are still open in 14 days.  Experts, please post closing recommendations before that time.

Below are your open questions as of today.  Questions which have been inactive for 21 days or longer are considered to be abandoned and for those, your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> YOU CANNOT DELETE A QUESTION with comments; special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click this link for Help Desk, Guidelines/Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Click you Member Profile to view your question history and please keep them updated. If you are a KnowledgePro user, use the Power Search option to find them.  

Questions which are LOCKED with a Proposed Answer but do not help you, should be rejected with comments added.  When you grade the question less than an A, please comment as to why.  This helps all involved, as well as others who may access this item in the future.  PLEASE DO NOT AWARD POINTS TO ME.

To view your open questions, please click the following link(s) and keep them all current with updates.
http://www.experts-exchange.com/questions/Q.11576379.html
http://www.experts-exchange.com/questions/Q.11771660.html
http://www.experts-exchange.com/questions/Q.20021632.html
http://www.experts-exchange.com/questions/Q.20021633.html
http://www.experts-exchange.com/questions/Q.20073130.html
http://www.experts-exchange.com/questions/Q.20074958.html
http://www.experts-exchange.com/questions/Q.20093305.html
http://www.experts-exchange.com/questions/Q.20174832.html
http://www.experts-exchange.com/questions/Q.20188009.html
http://www.experts-exchange.com/questions/Q.20257016.html
http://www.experts-exchange.com/questions/Q.20264169.html
http://www.experts-exchange.com/questions/Q.20272528.html
http://www.experts-exchange.com/questions/Q.20279237.html
http://www.experts-exchange.com/questions/Q.20283179.html
http://www.experts-exchange.com/questions/Q.20285545.html
http://www.experts-exchange.com/questions/Q.20287951.html
http://www.experts-exchange.com/questions/Q.20291697.html
http://www.experts-exchange.com/questions/Q.20293847.html



*****  E X P E R T S    P L E A S E  ******  Leave your closing recommendations.
If you are interested in the cleanup effort, please click this link
http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643
POINTS FOR EXPERTS awaiting comments are listed in the link below
http://www.experts-exchange.com/commspt/Q.20277028.html
 
Moderators will finalize this question if in @14 days Asker has not responded.  This will be moved to the PAQ (Previously Asked Questions) at zero points, deleted or awarded.
 
Thanks everyone.
Moondancer
Moderator @ Experts Exchange
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now