I have created a class with a member function and a structure which has a function pointer to the member function as an attribute. I have initialized the structure with the address of the member function. Then I have created an object for that class in main function and invoked the pointer to a member function by "(->*)". But It was failed with an error stating that "error: 'right operand' was not declared in this scope"
//Header
#ifndef A_H
#define A_H
class A
{
public:
typedef struct
{
void (A::*fptr) ();
}test;
test t;
public:
A();
virtual ~A();
void display();
protected:
private:
};
#endif // A_H
//A.cpp
#include "A.h"
#include <iostream>
using namespace std;
A::A()
{
t.fptr = &A::display;
}
A::~A()
{
//dtor
}
void A::display()
{
cout << "A::Display function invoked" << endl;
}
//Main
#include <iostream>
#include "A.h"
using namespace std;
int main()
{
cout << "Pointer to Member Function!" << endl;
A *obj = new A;
(obj->*t.fptr)();
return 0;
}
||=== Build: Debug in fptr (compiler: GNU GCC Compiler) ===| In function 'int main()':| error: 't' was not declared in this scope| ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|
Pointer to member functions are always hard to get right. But you're almost there. First, change the invocation to
(obj->*obj->t.fptr)();
and then think again whether you really need to go with plain pointer to members nested in a struct of the very same class you're pointing into, or whether some type aliases or other approaches could beautify the above monster :)