It is currently Sat May 27, 2017 8:42 am

All times are UTC - 5 hours




 Page 1 of 1 [ 4 posts ] 
Author Message
 Post subject: Function Pointer with classes
PostPosted: Wed Nov 23, 2011 7:35 pm 

Joined: Tue Nov 22, 2011 4:59 pm
Posts: 12
Im getting very frustrated. I needed to brush up on function pointers because I couldnt remember the syntax. I did a search on function pointers and found a website dedicated to it. I was able to get the normal c function style function pointer working. it took all of 30 seconds and I got several tests working. however I cant get a function pointer working in c++ with classes. can someone do up an example.


Offline
 Profile  
 
 Post subject: Re: Function Pointer with classes
PostPosted: Thu Nov 24, 2011 6:00 am 
Site Admin

Joined: Sun Feb 11, 2007 8:59 am
Posts: 1094
Location: Ontario Canada
Have a look at the following sites for help:
http://www.newty.de/fpt/index.html
http://oopweb.com/CPP/Documents/Functio ... m_fpt.html

If you google c++ function pointer example you'll find many more references to help you out.


Offline
 Profile  
 
 Post subject: Re: Function Pointer with classes
PostPosted: Thu Nov 24, 2011 8:15 am 

Joined: Tue Nov 22, 2011 4:59 pm
Posts: 12
fixed my problem. the problem was something like below wasnt working. (class omitted) it turned out because it was at global scope. see my last post for full working code :)

void (test::*pt2Member)(); // this compiles ok

// cant do this at global scope
pt2Member = &test::print; // this doesnt compile



Last edited by Kangum on Sat Nov 26, 2011 9:11 am, edited 3 times in total.

Offline
 Profile  
 
 Post subject: Re: Function Pointer with classes
PostPosted: Sat Nov 26, 2011 8:58 am 

Joined: Tue Nov 22, 2011 4:59 pm
Posts: 12
ok i figured it out. basically you cant reassign it at global scope outside of the declaration. if you reassign it within main it works fine.


#include <iostream>
#include <string>

using namespace std;

class test
{
public:
   test(string strtest):mtest(strtest){}

   string print() { return mtest; }
   string printalso() { return mtest + " print also\n"; }

private:
   string mtest;
};

string(test::*doit)();

int main(int argc, char** argv[])
{
        // works ok now
   doit = &test::print;

   test mytest("hello world\n");
   cout << (mytest.*doit)();

        // yay works
   doit = &test::printalso;
   cout << (mytest.*doit)();

   system("pause");
}


Offline
 Profile  
 
Display posts from previous:  Sort by  
 Page 1 of 1 [ 4 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Jump to:  

cron