Array of function pointers in C++

Go4Expert Member
20Sep2009,18:23   #1
punith's Avatar
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
Mentor
25Sep2009,15:59   #2
xpi0t0s's Avatar
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])();
}
Go4Expert Member
26Oct2009,13:42   #3
punith's Avatar
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;