1

with the visual c++ x86 compiler, the show function can be called, but the property a of the class Demo will be a random number in memory, I try to call in the way of comment, But it's useless, can someone help me how to call this function in a right way

#include <iostream>
using namespace std;

class Demo {
public:
  int a;
  Demo(int a) :a(a) {};
  virtual void show();
};

void Demo::show() {
  cout << "a: " << a << endl;
}


int main() {
  //typedef void (*func)(Demo * stu);
  typedef void (*func)();
  Demo d(100);
  func f = (func)*((int*)*(int*)(&d));
  //f(&stu);
  f();
  return 0;
}
math-chen
  • 31
  • 2
  • 7
    `func f = (func)*((int*)*(int*)(&d));` -- What are you really trying to accomplish with this line of code? Better yet, what are you really trying to accomplish, on a high-level? This is looking like an [XY Problem](https://xyproblem.info/). – PaulMcKenzie Jul 05 '22 at 02:59
  • 1
    "the show function can be called" What part of the code is supposed to cause that function to be called? According to what logic? Please try to explain your reasoning, step by step. – Karl Knechtel Jul 05 '22 at 03:00
  • according to the memory model, I try to fetch the virtual method ***show*** in the class by the way, I just want to verify the memory model – math-chen Jul 05 '22 at 03:02
  • *according to the memory model* -- What do you mean by "memory model"? That is not a term used in C++, unless you are talking about C++ programs from a bygone day written for the MSDOS operating system. – PaulMcKenzie Jul 05 '22 at 03:07
  • C++ does not dictate how virtual methods are actually implemented, so even the much used vtable approach is not mandatory. So, not to disappoint you, in that respect your question is not even valid. Still not clear to me why you would want to "fetch" the function pointer, what where you planning on doing with it? To call the virtual function you would just need to call `d.show()` like any other member function. – Pepijn Kramer Jul 05 '22 at 03:27
  • I agree with you, but I pointed out the specific compiler, the 32 bit visual c++ compiler,There is a specific implementation,so the instance have no problem@PepijnKramer – math-chen Jul 05 '22 at 04:19
  • thanks, I find the solution in the reference,Although this way is not very elegant @KarlKnechtel – math-chen Jul 05 '22 at 04:20

1 Answers1

0

Your void show() is not a func. No way. It never will be. End of story. The reinterpretation you've done is called undefined behavior, and it will only bring you tears down the road.

If you want a function-like object, you're looking for std::function.

Demo d(100);
std::function<void()> f = [&]() { d.show(); };
f();

std::function is a type compatible with any function-like objects, including function pointers, functors, and (in our particular case) anonymous closures.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116