Thread: how to convert return type of function at run time ?

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    11

    how to convert return type of function at run time ?

    Hi friends,
    I have a function pointer array of void type for some functions with different return types, I want to typecast the return type of function at run time. Any one have idea how to do this ?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    What exactly are you trying to solve? It may be the case that proper use of inheritance and polymorphism would be a better solution.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Well this would be the most logical way:
    Code:
    derived_type& var = dynamic_cast<derived_type&>( base_type_var );
    But since you're using void* pointers, you'd have to know what the actual type is.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Assuming you are not interested in C++ solutions as suggested, really, why not use a struct instead of an array, if the functions have different return types? This is the customary way to solve this type of problem.

    How about this obfuscation example:
    Code:
    #include <iostream>
    
    int func1();
    double func2();
    char func3(int x);
    
    typedef void (*voidfunc)();
    
    voidfunc array[3] = { reinterpret_cast<voidfunc>(func1), reinterpret_cast<voidfunc>(func2), 
    					  reinterpret_cast<voidfunc>(func3) };
    
    
    int func1()
    {
    	return 3;
    }
    double func2()
    {
    	return 6.7;
    }
    
    char func3(int x)
    {
    	return 'a' + static_cast<char>(x);
    }
    
    int main()
    {
    	std::cout << reinterpret_cast<int (*)(void)>(array[0])() << std::endl;
    	std::cout << reinterpret_cast<double (*)(void)>(array[1])() << std::endl;
    	std::cout << reinterpret_cast<char (*)(int)>(array[2])(6) << std::endl;
    	std::cout << static_cast<int>(reinterpret_cast<char (*)(int)>(array[1])(11)) << std::endl;
            return 0;
    }
    Output:
    3
    6.7
    g
    -52


    Note that the last line shows how easy it is to make a mistake - it calls a function returning a double with no parameters, but it's got a parameter, and expects a char return.

    And if any of my collegues showed me code like this, I would probably throw something hard at him/her.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    Jan 2008
    Posts
    11

    How to convert return type of function at run time ?

    This code is written for TURBO C++ 3.0 version

    Code:
    #include<iostream.h>
    #include<stdio.h>
    #include<conio.h>
    
    #define EVENTS  5
    #define OBJ_FUN 2
    
    class store
    {
    	  int qty;
      public: int Fn_stor()
    	  {
    	    cout<<"I'm in Fn_stor function of class store \n";
    	    return 5;
    	  }
    
    	  int Fn_quant()
    	  {
    	    cout<<"I'm in Fn_quant function of class store \n";
    	    return 0;
    	  }
    
    	  int Fn_get()
    	  {
    	    cout<<"I'm in Fn_get function of class store \n";
    	    return 6;
    	  }
    };
    
    class purc
    {
      public: int Fn_pur()
    	  {
    	    cout<<"I'm in Fn_pur function of class purc \n";
    	    return 7;
    	  }
    	  int Fn_order()
    	  {
    	    cout<<"I'm in Fn_order function of class purc \n";
    	    return 8;
    	  }
    	  int Fn_amount()
    	  {
    	    cout<<"I'm in Fn_amount function of class purc \n";
    	    return 9;
    
    	  }
    };
    
    class manu
    {
    public: int Fn_man()
    	{
    	 cout<<"I'm in Fn_manu function of class manu \n";
    	 return 2;
    	}
    	int Fn_Time()
    	{
    	 cout<<"I'm in Fn_Time function of class manu \n";
    	 return 3;
    	}
    	int Fn_work()
    	{
    	  cout<<"I'm in Fn_work function of class manu \n";
    	 return 4;
    	}
    };
    
    class Generic : public store, public purc, public manu
    {
    };
    
    void main()
    {
    store str;
    purc prc;
    manu mnf;
    int class_id,Fn_id;
    
    int (Generic::*pt[3][3])() = {
    (&store::Fn_stor,&store::Fn_quant,&store::Fn_get),
    (&purc::Fn_pur,&purc::Fn_amount,&purc::Fn_order),
    (&manu::Fn_man,&manu::Fn_Time,&manu::Fn_work)
    };
    
    clrscr();
    
    enum { C_STOR,C_PURC,C_MANF };
    enum { Fn1,Fn2,Fn3 };
    
    void *obj_ptr[] = { &str,&prc,&mnf };
    
    
    
    int seq[EVENTS][OBJ_FUN] = {
    			      {C_STOR,Fn2},
    			      {C_PURC,Fn1},
    			      {C_STOR,Fn3},
    			      {C_MANF,Fn1},
    			      {C_PURC,Fn2}
    
    			      };
    
    for(int counter=0;counter<EVENTS;counter++)
    {
    class_id = seq[counter][0];
    Fn_id    = seq[counter][1];
    ((Generic*)obj_ptr[class_id]->*pt[class_id][Fn_id])();
    } 
    getch();
    }
    Here, all function are of return type int and I have created class Generic for type casting of object at run time , because I will be not knowing which object user is going to call. Like this if the functions are of different return types then how I can type cast it at run time ?

    Vinod !!

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    All three classes appear to have nothing in common. There is nothing generic to speak of concerning them.

    I think you are making this more complicated than it should be. Just use normal if-else conditional logic to decide which class to instantiate and use.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Jan 2008
    Posts
    11
    I have created Generic class because at run time I need to typecast the object. The Generic class inherited all 3 classes so compiler will do typecasting of object to me at ((Generic*)obj_ptr[class_id]->*pt[class_id][Fn_id])(); line. I think you got it. Like this I want to typecast the return type of function when the functions having different return types

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I have created Generic class because at run time I need to typecast the object.
    You don't need to typecast at all. You are trying to solve your problem in the wrong way.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Jan 2008
    Posts
    11

    how to convert return type of function at run time ?

    Then how can you call member function without type casting the object ?
    If I wan to call member function of store class then I need store class object right ! so that I need to typecast !!!

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Then how can you call member function without type casting the object ?
    If I wan to call member function of store class then I need store class object right ! so that I need to typecast !!!
    My point is that there is nothing in common between your classes. Furthermore, with multiple inheritance, your Generic class is a store class, so you actually can use non-private members from the store class directly. There is no typecasting needed.

    But why bother with multiple inheritance in the first place? Why not just instantiate store objects, purc objects and manu objects when the logic dictates that they are needed?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    The typical case is that you have similar, but slightly different functionalit, in the form of polymorphic classes.

    Your classes appear to have nothing in common - so why would you actually want to operate on them from a common piece of code in any form.

    If you have polymorphic problem, you can solve it by a having virtual functions defined in a base-class, and then inherit that base-class into other, so called derived objects. That way, a function using the base-class can access the functionality of any of the derived classes.

    For example:
    Code:
    class vehicle
    {
    public:
       virtual int maxLegalWeight();
       virtual int maxWheels();
       virtual string poweredBy();
    };
    
    class bicycle: public vehicle
    {
    public:
       int maxLegalWeight() { return 200; }
       int maxWheels() { return 3; }
       string poweredBy() { return "Human power"; }
    };
    
    class car: public vehicle 
    {
    public:
       int maxLegalWeight() { return 3500; }
       int maxWheels() { return 4; }
       string poweredBy() { return "Petrol/Diesel engine"; }
    };
    
    class steamtrain: public vehicle
    {
    public:
       int maxLegalWeight() { return 200000; }
       int maxWheels() { return 500; }
       string poweredBy() { return "Steam generated from coal"; } 
    };
    But if the classes have nothing in common, there is no point in trying to MAKE them common.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    Registered User
    Join Date
    Jan 2008
    Posts
    11

    how to convert return type of function at run time ?

    But I'm giving option to user that which object and which function to be called at run time. So user will enter only numbers. If He enters 1,1 then it means store object is calling Fn_stor(). So that I want to create 3 objects to store in function pointer array.

  13. #13
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Why do you want the user to do that? What is the common factor for the functions you are going to use?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    void main is undefined. Don't use it.
    Indentation needs work. It's important so we can read the code. Read http://cpwiki.sf.net/Indentaiton.
    Last edited by Elysia; 01-26-2008 at 11:08 AM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Registered User
    Join Date
    Jan 2008
    Posts
    11
    Nothing common factor in functions. For Example,in Micrsoft Paint brush user will select the circle object and draw it means he can use any object at any time . If in some situation there are 500 of classes then I need to create 500 objects and I need to write switch case for 500 times for 500 objects. If I code like this then no need to write switch case. The ((Generic*)obj_ptr[class_id]->*pt[class_id][Fn_id])(); line will do all things for me ! right

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  2. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  3. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  4. Question on l-values.
    By Hulag in forum C++ Programming
    Replies: 6
    Last Post: 10-13-2005, 04:33 PM
  5. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM