CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Oct 2001
    Location
    CA,USA
    Posts
    60

    A quick question on VTBL




    Is there a way where i can call a function in
    a class without using the name of the function.

    class A
    {
    public :
    int x
    void print(){cout<<"Hello";}
    };

    A *a;
    then using this pointer call print function
    without using the name. I dont want to use
    a->print();

    I am in this situation beacuse i have the name of the function in database. using that name and the name of the class i want to call the function.





    Please rate the article if it is of any use to you. This encourages me to reply more and more and more.

  2. #2
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: A quick question on VTBL

    That isn't a question of v-tables because print is not virtual in A.

    However if you want you could do this:

    class IPrint // interface implements printing
    {
    public:
    virtual void print() = 0;
    virtual ~IPrint();
    };



    Now you can have different instances of classes that derive from IPrint and override printing (in their own way).

    However your "database" can store an array of IPrint pointers (possible shared-pointers), and not have to know the exact class that they point to.



    The best things come to those who rate

  3. #3
    Join Date
    Apr 2000
    Location
    Frederick, Maryland
    Posts
    507

    Re: A quick question on VTBL

    If the function is virtual then you can call it via table. Here is a small program to show this.


    // call virtual function without using its name
    #include <iostream>
    using namespace std;

    class Base {
    public:
    virtual void Fun1() {
    cout << "Base::Fun1" << endl;
    }
    virtual void Fun2() {
    cout << "Base::Fun2" << endl;
    }
    };

    typedef void(*Fun)();

    int main() {
    Base obj;

    // declare function pointer
    Fun pFun = NULL;

    // call first virtual function
    pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+0);
    pFun();

    // call second virtual function
    pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+1);
    pFun();

    return 0;
    }




    Hope it helps.



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured