I am trying to create object of another class in one class (I am able to do this) and I want to pass a method of the first class to the second class as constructor argument (I am not able to do this. I get compiler errors). Below is the code.
#include <iostream>
using namespace std;
class B
{
public:
B(void (*fp)(void))
{
fp();
}
private:
};
class A
{
public:
void printHelloWorld()
{
cout << "Hello World!" << endl;
}
private:
B ObjB{printHelloWorld};
};
int main()
{
cout << "!!** Program Start **!!" << endl;
A ObjA;
cout << "!!** Program End **!!" << endl;
return 0;
}
I receive the following Errors.
main.cpp:21:27: error: could not convert ‘{((A*)this)->A::printHelloWorld}’ from ‘’ to ‘B’
21 | B ObjB{printHelloWorld};
| ^
| |
| <brace-enclosed initializer list>
The code can be compiled on this link also https://onlinegdb.com/xB70hwQph
The code works fine if I make printHelloWorld
as static function or Shift the defination of printHelloWorld
outside the class.
I am looking for a solution for this simple looking problem.