1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Array of function pointers in C++

Discussion in 'C++' started by punith, Sep 20, 2009.

  1. punith

    punith New Member

    Joined:
    Sep 4, 2007
    Messages:
    18
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    ALP programmer
    Hi All,

    I was trying out a simple program to understand array of function pointers in C++.
    Code:
    #include <iostream>
    
    class a
    {
    
      public:
      void func_1 ();
      void func_2();
      void (a::*arrfptr[2])();
      a();
    };
    
    void a::func_1()
    {
      std::cout<<"\n func_1\n";
    }
    void a::func_2()
    {
      std::cout<<"\n func_2\n";
    }
    a::a()
    {
      a::arrfptr[0]=& a::func_1;
      a::arrfptr[1]=& a::func_2;
    }
    
    class b
    {
      public:
      void func_b();
    };
    
    void b::func_b()
    {
       a obj;
       (obj.*arrfptr[0]) ();
       (obj.*arrfptr[1]) ();
    }
    
    int main()
    
    {
      b o;
      o.func_b();
    }
    
    

    while compiling I am getting this error
    Code:
    [root@localhost example]# g++ fptr.cpp
    fptr.cpp: In member function ‘void b::func_b()’:
    fptr.cpp:36: error: ‘arrfptr’ was not declared in this scope
    [root@localhost example]# 
    
    arrfptr is public in class a then why i am not able to access it in class b ?

    Thanking you in Advance
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    You have to make the functions static to be able to take their addresses. This is because of the way object orientation works; if an object doesn't exist, then its functions don't exist either, so to make the functions exist whether or not there is an object in existence then the functions have to be static.
    Code:
    class a
    {
    
      public:
      static void func_1 ();
      static void func_2();
      void (*arrfptr[2])();
      a();
    };
    
    void a::func_1()
    {
      std::cout<<"\n func_1\n";
    }
    void a::func_2()
    {
      std::cout<<"\n func_2\n";
    }
    a::a()
    {
    	arrfptr[0]=&func_1;
    	arrfptr[1]=&func_2;
    }
    
    class b
    {
      public:
      void func_b();
    };
    
    void b::func_b()
    {
       a obj;
       (obj.arrfptr[0])();
       (obj.arrfptr[1])();
    }
    
     
  3. punith

    punith New Member

    Joined:
    Sep 4, 2007
    Messages:
    18
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    ALP programmer
    Hi,
    thanks it works now, but as you said if object dosen't exist then function dosen't exist, but I am creating the object
    Code:
    a obj;
    
     

Share This Page