Home > Net >  Create a pointer that points to a member function that takes a struct as an argument
Create a pointer that points to a member function that takes a struct as an argument

Time:06-27

I have main.cpp file where I defined a struct:

struct values {
        string name1;
        string name2;
        int key ;
        
    } a;

A class named Encrypt defined in a header file Encrypt.h and a file Encrypt.cpp where I define my functions... Im trying to create a pointer that points to a function that has a struct type as parameter here's how I did it: in my header file Encrypt.h


#ifndef Encrypt_h
#define Encrypt_h
#include<iostream>
using namespace std;
class Encrypt {
public:
    void print(void *);
};
#endif /* Encrypt_h */

in my Encrypt.cpp :

void Encrypt::print(void * args)
{
    struct values *a = args;
     string name= a.name1;

    cout<<"I'm"<<name<<endl;

};

here's how I tried to create the pointer in main.cpp

   void (Encrypt::* pointer_to_print) (void * args) = &Encrypt::print;

THE ERROR I GET :

" Cannot initialize a variable of type 'struct values *' with an lvalue of type 'void *' " in Encrypt.cpp

the line :

 struct values *a = args; 

REMARQUE

Im doing this because I want to pass a function with more than 2 parameters to the function : pthread_create() so my function print is just I simplified example.

CodePudding user response:

The problem is that args is of type void* and a is of type values* so you get the mentioned error.

To solve this uou can use static_cast to cast args to values* if you're sure that the cast is allowed:

values *a = static_cast<values*>(args);

Additionally change a.name1 to a->name1.

Demo

  • Related