-1

I have this class and I am trying to extract x1 function from pointer of my class pointer

class myclass
{
public:
myclass();
~myclass();
int x = 0;
int x1();
private:



};

int myclass::x1() 
{
return 100;
}

like this

myclass* ptr = new myclass[10];
for (int i = 0; i < 10; i++)
ptr[i].x = i*11;
for (int i = 0; i < 10; i++)
{
 std::cout << ((ptr + i)->x) << std::endl;
 void *v = (void *)((ptr + i)->x);
 typedef int (*fptr)()=//what I need to do to v to get x1 function and call it; 
    
}

can I do this. Is this allowed in C++. I am using VS2019

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
dev
  • 3
  • 2
  • If you _could_ get an `int(*)()` for a member function, and you called it (with no arguments), what would `this->x` be during the call? – Davis Herring May 23 '23 at 06:01

2 Answers2

1

You may use pointer to member functions. The syntax is like:

int (myclass::*myFuncPtr)() = &myclass::x1;
// call it by object 
(object.*myFuncPtr)();
// or by the pointer of the object
(objectPtr->*myFuncPtr)();

A more modern way is:

using MyFuncPtr = decltype(&myclass::x1);
MyFuncPtr myFuncPtr = &myclass::x1;
// both by object
std::invoke(myFuncPtr, object);
// and by pointer is correct
std::invoke(myFuncPtr, objectPtr);

Notice that you must provide an object for this in the member function. Only static member functions can be directly called without being bound to an object.

You may refer to my previous answer to know more about it.

o_oTurtle
  • 1,091
  • 3
  • 12
0

In C++, you cannot directly access member functions through a pointer to a member variable. To access and call the x1 function of your class, you need to have a pointer to an instance of myclass, not just a pointer to a member variable.

myclass* ptr = new myclass[10];
for (int i = 0; i < 10; i++)
    ptr[i].x = i * 11;

for (int i = 0; i < 10; i++)
{
    std::cout << ((ptr + i)->x) << std::endl;
    myclass* instance = ptr + i; // Get the pointer to the current instance

    int result = instance->x1(); // Call the x1 function

    std::cout << "x1 result: " << result << std::endl;
}

delete[] ptr; // Delete the allocated memory
hexlp
  • 71
  • 3
  • can u please tell what version of C++ does VS2019 uses – dev May 23 '23 at 06:05
  • Visual Studio 2019 supports multiple versions of C++. The specific version depends on the compiler version and the project settings. To determine the exact version, you can check the project settings, right-click on the project in the Solution Explorer and select "Properties" from the context menu than "Configuration Properties" -> "General" look for the "C++ Language Standard" or "C++ Language Standard" option. – hexlp May 23 '23 at 06:13