C++ static array in method - c++

One can use static array in method for performance if the method frequently called like
static char [1024];
What I want to ask is , if the array size is small like 128 or 64 which one is more advantageous from the samples one and two.
Sample 1:
void foo(){
static mArr char[128];
memset(mArr,0x0,128);//not sure if this line is necessary but I think its a must , any commends appriciated.
}
Sample 2:
void foo(){
char mArr[128];
}

Sample 3:
void foo() {
char mArr[128] = {0};
}

Little actual difference, the latter basicly just adds 128 to the stack-pointer.
if you only must do the clearing at first run, there can be a saving in:
static char mArr[128] = {0} ;
the memset is only necessary if the array is need to be zeroed-out every time, there's nothing 'magic' with static;

Version 1:
void foo() {
static char a[128];
memset(a,0x0,128);
// use a
}
Allocates a on the heap and provides memory which is persistent over all function calls. a works a bit like a global variable with all the problems of global variables. For example, this version will be problematic if the function is called from multiple threads.
Version 2:
void foo() {
char a[128] = {0};
// use a
}
Allocates a on the stack each time the function is called. ={0} initializes with 0 ( every time the function is called). Use this if you do not need the memory to be persistent over several function calls.

Definitely sample 2 - sample 1 would not compile (first char, then variable name ;)
Anyway, static means the array is set on a fixed position in memory while in sample 2 the array is put on the stack. This is not about advantageous - it's about what you need.
Use 1) if you want to call foo more than once and you always want to use the same array and it should keep it's contents between the calls (without the memset).
Use 2) if you want to use the array just in this function and have a "fresh" array every time you call it.
You do not need the memset - it would just clear the array every time you call foo. While that may be a good thing, it definitely is pointless in combination with static, except you do:
void foo()
{
static mArr char[128];
static bool firstrun = true;
if(firstrun)
{
memset(mArr,0x0,128);
firstrun = false;
}
}
In this case, firstrun would be used to initialize your function at the first run and leave it as is in the following runs.
For using "static" have a look at this article.

I would choose Sample 1 but you maybe need to reconsider memset.
Lets review these senarios:
a) You need to empty the array each time foo() is called.
b) You do not need to empty the array each time foo() is called.
For a:
void foo()
{
char mArr[128] = {0};
}
For b:
void foo()
{
static mArr[128] = {0};
}

Related

what are pros and cons to define constant local variables as static ( c++)?

void Animation::playAnimation() const
{
static const int index = 0;
const std::string& animationFileName = m_animationContainer.getAnimationName(index);
static const int zOrder = -1;
static bool isLooping = false;
AnimationBank::play(animationFileName,
zOrder,
isLooping);
}
what are pros and cons to define constant local variables as static?
what is an overhead of defining index, zOrder, isLooping as static. Is there any benefit to do this?
In general case if you declare a static variable inside of a function then it will be initialized during first use. In order to achieve this behavior another global static variable of boolean type will be created by the compiler. It will be initially set to false and then set to true after related static variable is initialized.
In your case there is no point to declare any variables as static.
Yes, you will have a little bit overhead when using static variables in function, since each time your program execute that function it has to check whether these static variables initialized.
Let's start with the easy one.
const:
const doesn't give you any ovehead and the only advantage it give you is the variable can't be changed during its life time. It is interesting because:
Correctness.
If want a that show clearly show what the variable, use const make clear that variable won't/can't be changed.
You may think, why I don't use a #define for example. Well, define will make the compiler replace it to fix values and in some cases it is not and advantage like strings or objects.
Protection.
If someone else qill use your function you make clear this variable can be changed and you protect its value.
Static:
Static give you a overhead because after create the variable for the first time it will exist during the lifetime of your program and the advantage is exactly that. When the variable is create you give it an value. Because it stay alive after that, no matter what happens, it can't get again a value as it the is the first time.
Lets see an example with class.
Suppose you want a class to manager an addition to one int and this int need to accumulate this additions including a new object of this class is created and or destroyed:
#include <iostream>
using namespace std;
class ClassAcInt {
public:
void Print_iVar();
void Add_iVar();
private:
static int iVar;
};
int ClassAcInt::iVar = 10; //iVar = 10
void ClassAcInt::Print_iVar() { //Show iVar
cout << iVar << '\n';
}
void ClassAcInt::Add_iVar() { //Add 1 to iVar
iVar++;
}
int main () {
ClassAcInt* oC1 = new ClassAcInt(); //iVar = 10
oC1->Print_iVar(); //print iVar
oC1->Add_iVar(); //iVar = iVar + 1
oC1->Print_iVar(); //Print iVar
delete oC1; //Bye what we did... Are you sure?
ClassAcInt* oC2 = new ClassAcInt(); //iVar = 10? Are you sure?
oC2->Print_iVar(); //Print iVar.... What a hack!!!!
oC2->Add_iVar(); //iVar = iVAr + 1
oC2->Print_iVar(); //omgosh...
delete oC2;
}
You can think the result will be:
10
11
10
11
but 'surprisingly' the result is:
10
11
11
12
The key is the lines static int iVar; and int ClassAcInt::iVar = 10;. Try to suppress the static word and see what happens :)

Get call identifier or address of a function

Suppose that I have this code:
class MyClass
{
public:
void SomeFunction()
{
// Find somehow if this is first, second, or third call of a function in a main loop
// If the function is called first time create new variables that will be used just for this function call
}
};
MyClass myClassObject;
int main()
{
myClassObject.SomeFunction(); // First call
myClassObject.SomeFunction(); // Second call
myClassObject.SomeFunction(); // Third call
}
How can I know inside function what number of call is it?
Note that I will probably have 100 function calls placed in code. Also this should work in Visual Studio on Windows and Clang on Mac.
I had one workaround:
void SomeFunction(const char* indetifier = "address")
{
CheckAddress(indetifier); // This will check if address is stored. If it is not, create variables, if it is, if addresses matches use variables that are tied to that address.
}
I tried not to assign a new string to an "indetifier" and to let it to use default string ("address"). This of course didn't worked well as compiler will optimize "indetifier", so I was thinking that maybe a solution would be to disable optimizations for that variable, but I didn't because there should be some more elegant solution.
Also one thing came on my mind, maybe I could force inline a function and then get it's address, but this also seams like bad workaround.
I could also create new classes for every call but I would like to avoid this as there will be a lot of function calls and I don't want to think 100 different names.
If there is a way to create class object only at first call this would be awesome.
I hope that you understand what I want, sorry if something is not that clear as I am beginner coder.. :D
EDIT:
I can't use static for variables in a class because software that I am developing is a plugin that could have multiple instances loaded inside host and this will probably mess up the variables. I have tested static variables and if I create for example "static int value" anywhere and write something in it in one instance of a plugin this "value" will be updated for all instances of a plugin and this is not something that I want.
void SomeFunction()
{
// Find somehow if this is first, second, or third call of a function in a main loop
// If the function is called first time create new variables that will be used just for this function call
}
If the first call is to be tracked per object, then you need a member variable that keeps track of how many times SomeFuntion has been called for that object.
If the first call is to be tracked independent of objects, then you can use a static function variable that keeps track of how many times SomeFuntion has been called for that object.
I can't use static for variables in a class because software that I am developing is a plugin that could have multiple instances loaded inside host and this will probably mess up the variables. I have tested static variables and if I create for example "static int value" anywhere and write something in it in one instance of a plugin this "value" will be updated for all instances of a plugin and this is not something that I want.
So make a non-static counter?
class MyClass {
int count;
public:
MyClass () : count(0) { }
void SomeFunction () {
++ count;
// do stuff with 'count'
}
};
MyClass myClassObject;
int main () {
myClassObject.SomeFunction(); // First call
myClassObject.SomeFunction(); // Second call
myClassObject.SomeFunction(); // Third call
}
Or just pass it as a parameter...
class MyClass {
public:
void SomeFunction (int count) {
// do stuff with 'count'
}
};
MyClass myClassObject;
int main () {
myClassObject.SomeFunction(1); // First call
myClassObject.SomeFunction(2); // Second call
myClassObject.SomeFunction(3); // Third call
}
But I'm really wondering what you're actually trying to do, and I highly suggest sitting back and rethinking this whole thing, because there are a number of red flags / confusing points here...
If you're only interested in checking whether it's the first call, you can add a bool SomeFunction_first_call; to the MyClass, to act as a flag. The constructor sets the bool to true. MyClass::SomeFunction() uses the conditional check if (SomeFunction_first_call) /* ... */ to determine whether it's the first call, as follows:
class MyClass
{
bool SomeFunction_first_call;
public:
MyClass() : SomeFunction_first_call(true) {}
void SomeFunction()
{
if (SomeFunction_first_call)
{
// This code only executes on first call.
do_something();
// Successfully handled first call, set flag to false.
SomeFunction_first_call = false;
}
// This code always executes.
do_something();
}
};
Similarly, if you're only concerned about the first HOWEVER_MANY_CALLS calls, where HOWEVER_MANY_CALLS is a number, you can use something like this:
#include <cstdint>
class MyClass
{
uint8_t SomeFunction_calls;
public:
MyClass() : SomeFunction_calls(0) {}
void SomeFunction()
{
// This segment will be executed until (SomeFunction_calls == HOWEVER_MANY_CALLS).
// After this, the segment will be skipped, and the counter will no longer increment.
if (SomeFunction_calls < HOWEVER_MANY_CALLS)
{
// This code only executes on first HOWEVER_MANY_CALLS calls.
do_something();
// Increment counter.
++SomeFunction_calls;
}
// This code always executes.
do_something();
}
};
Make sure to use the appropriately signed variable for the number of calls that need special handling (i.e. uint8_t for 0..255, uint16_t for 256..65,535, etc.). If different instances of MyClass will need to keep track of a different number of calls, then use a non-type template parameter to indicate this, and optionally, a defaulted typename to indicate what type the counter should be.
#include <cstdint>
template<uint64_t N, typename T = uint64_t>
class MyClass {
T SomeFunction_calls;
...
void SomeFunction()
{
if (SomeFunction_calls < N) {
...
}
...
}
};
In this case, a MyClass<4> will have special treatment for the first 4 calls to SomeFunction(), a MyClass<4444444444444444444> will have special treatment for the first 4,444,444,444,444,444,444 calls, and so on. The counter will default to uint64_t, as that should be large enough to hold the value; when only a smaller number of calls need special treatment, you can specify a smaller type, such as MyClass<4, uint8_t> or MyClass<444444444, uint32_t>.
In C++ you can use the static keyword in a local variable context to create the object only once at the first call:
#include <iostream>
struct MyObject {
MyObject() {
std::cout << "Creating instance " << this << "\n";
};
};
void foo() {
static MyObject my_instance;
std::cout << "... inside function foo ...\n";
}
int main(int argc, const char *argv[]) {
std::cout << "About to call foo...\n";
foo();
std::cout << "... second call ...\n";
foo();
std::cout << "... third call ...\n";
foo();
return 0;
}
With the above code you will notice that only on object MyObject will be created, on the first call to foo.
Note that if your function is a template then for each instantiation of the template you will get another distinct static variable. For example with:
template<int N>
void foo() {
static MyObject my_instance;
std::cout << "... inside function foo ...\n";
}
the all the calls to foo<1>() will use the same variable but calling instead foo<2>() will access another copy of the function (another instantiation of the function template), that will have its own distinct static variable created on the first call to foo<2>(). All static variables that have been initialized will be destroyed after the end of main when the program terminates.

Identify if object is allocated in static memory block (or how to avoid data race conditions)

Preface:
this question is closely related to these ones: ...
- C++: Avoiding Static Initialization Order Problems and Race Conditions Simultaneously
- How to detect where a block of memory was allocated?
... but they have NO positive solution and my actual target use-case is slightly different.
During construction of the object I need to know if it is initialized in static memory bock ( BSS) or is it instantiated in Heap.
The reasons are follow:
Object by itself is designed to be initialized to "all zeros" in constructor - therefore no initialization is needed if object is statically initialized - entire block with all objects is already set to zeros when program is loaded.
Static instances of the object can be used by other statically allocated objects and alter some member variables of the object
Order of initialization of static variables is not pre-determined - i.e. my target object can be invoked before its constructor is invoked, thus altering some of its data, and constructor can be invoked later according to some unknown order of initialization of statics thus clearing already altered data. That is why I'd like to disable code in constructor for statically allocated objects.
Note: in some scenarios Object is the subject for severe multi-threaded access (it has some InterlockedIncrement/Decrement logic), and it has to be completely initialized before any thread can touch it - what i can guaranteed if i explicitly allocate it in Heep, but not in static area (but i need it for static objects too).
Sample piece of code to illustrate the case:
struct MyObject
{
long counter;
MyObject() {
if( !isStaticallyAllocated() ) {
counter = 0;
}
}
void startSomething() { InterlockedIncrement(&counter); }
void endSomething() { InterlockedDecrement(&counter); }
};
At the moment I'm trying to check if 'this' pointer in some predefined range, but this does not work reliably.
LONG_PTR STATIC_START = 0x00400000;
LONG_PTR STATIC_END = 0x02000000;
bool isStatic = (((LONG_PTR)this >= STATIC_START) && (LONG_PTR)this < STATIC_END));
Update:
sample use-case where explicit new operator is not applicable. Code is 'pseudo code', just to illustrate the use-case.
struct SyncObject() {
long counter;
SyncObject() {
if( !isStaticallyAllocated() ) {
counter = 0;
} }
void enter() { while( counter > 0 ) sleep(); counter++; }
void leave() { counter--; }
}
template <class TEnum>
struct ConstWrapper {
SyncObject syncObj;
TEnum m_value;
operator TEnum() const { return m_value; }
LPCTSTR getName() {
syncObj.enter();
if( !initialized ) {
loadNames();
intialized = true;
}
syncObj.leave();
return names[m_value];
}
}
ConstWrapper<MyEnum> MyEnumValue1(MyEnum::Value1);
You can probably achieve this by overwriting the new operator for your class. In your customized new, you can set a "magic byte" within the allocated memory, which you can later check for. This will not permit distinguishing stack from heap, but statically from dynamically allocated objects, which might be sufficient. Note, however, that in the following case
class A {
};
class B {
A a;
};
//...
B* b = new B;
b.a will be considered statically allocated with the proposed method.
Edit: A cleaner, but more complicated solution is probably a further customization of new, where you can keep track of dynamically allocated memory blocks.
Second edit: If you just want to forbid static allocation, why don't you just make the constructor private and add a factory function to the class dynamically creating the object and delivering the pointer?
class A {
private:
A () { ... }
public:
static A* Create () { return new A; }
};
I think that the best way for you to control this is to create a factory for your class. That way you have complete control of how your objects are created instead of making complicated guesses over what memory is used.
The first answer is: not portably, and it may not be possible at all on
some platforms. Under Solaris (and I think Linux as well), there is an
implicitly defined global symbol end, comparison of arbitrary
addresses works, and if this < &end (after the appropriate
conversions), the variable is static, at least as long as no dynamic
loading is involved. But this is far from general. (And it definitely
fails anytime dynamic linking is involved, regardless of the platform.)
The solution I've used in the past was to make the distinction manually.
Basically, I designed the class so that the normal constructor did the
same thing as zero initialization, and I then provided a special no-op
constructor for use with static objects:
class MayBeStatic
{
public:
enum ForStatic { isStatic };
MayBeStatic() { /* equivalent of zero initialization */ };
MayBeStatic( ForStatic ) { /* do absolutely nothing! */ };
// ...
};
When defining an instance with static lifetime, you use the second
constructor:
MayBeStatic object( MayBeStatic::isStatic );
I don't think that this is guaranteed by the standard; I think the
implementation is allowed to modify the memory any way it wants before
invoking the constructor, and in particular, I think it is allowed to
"redo" the zero initialization immediately before invoking the
constructor. None do, however, so you're probably safe in practice.
Alternatively, you can wrap all static instances in a function, so that
they are local statics, and will be initialized the first time the
function is called:
MayBeStatic&
getStaticInstance()
{
static MayBeStatic theInstance;
return theInstance;
}
Of course, you'll need a separate function for each static instance.
It looks like after thinking for a while, I've found a workable solution to identify if block is in static area or not. Let me know, please, if there are potential pitfalls.
Designed for MS Windows, which is my target platform - by another OS I actually meant another version of MS Windows: XP -> Win7. The idea is to get address space of the loaded module (.exe or .dll) and check if block is within this address space. Code which calculates start/end of static area is put into 'lib' segment thus it should be executed before all other static objects from 'user' segment, i.e. constructor can assume that staticStart/End variables are already initialized.
#include <psapi.h>
#pragma warning(push)
#pragma warning(disable: 4073)
#pragma init_seg(compiler)
#pragma warning(pop)
HANDLE gDllHandle = (HANDLE)-1;
LONG_PTR staticStart = 0;
LONG_PTR staticEnd = 0;
struct StaticAreaLocator {
StaticAreaLocator() {
if( gDllHandle == (HANDLE)-1 )
gDllHandle = GetModuleHandle(NULL);
MODULEINFO mi;
GetModuleInformation(GetCurrentProcess(), (HMODULE)gDllHandle, &mi, sizeof(mi));
staticStart = (LONG_PTR)mi.lpBaseOfDll;
staticEnd = (LONG_PTR)mi.lpBaseOfDll + mi.SizeOfImage;
// ASSERT will fail in DLL code if gDllHandle not initialized properly
LONG_PTR current_address;
#if _WIN64
ASSERT(FALSE) // to be adopted later
#else
__asm {
call _here
_here: pop eax ; eax now holds the [EIP]
mov [current_address], eax
}
#endif
ASSERT((staticStart <= current_address) && (current_address < staticEnd));
atexit(cleanup);
}
static void cleanup();
};
StaticAreaLocator* staticAreaLocator = new StaticAreaLocator();
void StaticAreaLocator::cleanup() {
delete staticAreaLocator;
staticAreaLocator = NULL;
}

duplicate typedef struct through pointer

I have following typedef defined and *ButtonSettingPtr as a pointer:
typedef struct
{
void *next;
char** buttonsetting;
char* currentsetting;
uint16_t presetid;
uint16_t currentcounter;
uint16_t maxsize;
uint16_t buttonid;
} ButtonSetting;
typedef ButtonSetting *ButtonSettingPtr;
class Options {
private:
ButtonSettingPtr settings;
ButtonSettingPtr preset1;
public:
Options();
void newSetting(char** _setting, uint16_t _maxsize, uint16_t _buttonid);
// some other stuff defined here
}
With the newSetting() function I am adding several new entries to my
typedef instance! Now, I would like to save all these settings
(this->settings) into another pointer (this->preset1) via memcpy to
later call them up again via another function, since I am using
this->settings in a couple of other functions (getCurrentSetting) which
are working quite well etc.
char *Options::getCurrentSetting(uint16_t _buttonid) {
ButtonSettingPtr setting = (ButtonSettingPtr)this->settings;
while (setting != NULL)
{
if (setting->buttonid == _buttonid) {
char * tmpsetting =
setting->buttonsetting[setting->currentcounter];
return tmpsetting;
}
setting = (ButtonSettingPtr)setting->next;
}
return NULL;
}
Here's the problem:
void Options::savePreset() {
memcpy(&this->preset1,&this->settings,sizeof(&this->settings));
}
void Options::loadPreset() {
memcpy(&this->settings,&this->preset1,sizeof(&this->preset1));
}
It seems that my preset1 pointer is always exactly the same as
this->settings even though i am changing settings inbetween. I
understand that with the &amp sign it literally copies the address of
that pointer, so to no surprise they will both always be exactly the
same. But what I would like to copy is rather all bytes and point them
to preset1, so I can recall all the settings later again.
So, without the &amp sign my code just hangs:
void Options::savePreset() {
memcpy(this->preset1,this->settings,sizeof(this->settings));
}
void Options::loadPreset() {
memcpy(this->settings,this->preset1,sizeof(this->preset1));
}
Do I have to malloc the this->preset1 pointer before I memcpy everything
to it? The whole code is compiled using avr-libc for an atmega chip.
Thanks in advance for any useful hint!
ps: My understanding of C++ has been surely better when I was younger!
It looks like you're doing a home-grown singly linked list. If you replace that with std::vector you'll find that copying one to the other is as easy as preset1 = settings; (you don't need to put this-> in front of everything unless you just prefer that style).
You might also want to replace the char** inside the class with std::vector<string> as well, then the actual strings will be copied.
Yes, you do need to malloc preset1 (no need to dereference it with this-> inside a member function. If you want to make it clear that it's a class data member, name it m_preset1 or mPreset1 as you like).
So, in your constructor set preset1 to NULL. Then in your member function you can:
void Options::savePreset() {
if (preset1 == NULL) {
preset1 = (ButtonSettingPtr)malloc(sizeof (ButtonSetting));
}
memcpy(preset1, settings, sizeof(ButtonSetting));
}
Don't forget to add error checking. But really, I don't see any reason not to statically allocate space instead and avoid memory allocation issues:
class Options {
private:
ButtonSetting settings;
ButtonSetting preset1;
public:
Options();
void newSetting(char** _setting, uint16_t _maxsize, uint16_t _buttonid);
// some other stuff defined here
}
void Options::savePreset() {
memcpy(&preset1, &settings, sizeof(ButtonSetting));
}
Note that sizeof(this->settings) will always be 4 or 8 (depending on 32 or 64 bit CPU) because you're asking for the size of a pointer, not the size of the structure.
sizeof(&this->settings)
will return the size of a pointer because it is effectively a pointer.
sizeof(this->settings)
will return the size of a pointer because it is a pointer.
sizeof(*this->settings)
will return the size of the anonymous struct that settings points too.
And as for the question of needing to malloc space for
this->preset1
depends on you code. But it for sure needs to point to valid memory!

Creating function pointers to functions created at runtime

I would like to do something like:
for(int i=0;i<10;i++)
addresses[i] = & function(){ callSomeFunction(i) };
Basically, having an array of addresses of functions with behaviours related to a list of numbers.
If it's possible with external classes like Boost.Lambda is ok.
Edit: after some discussion I've come to conclusion that I wasn't explicit enough. Please read Creating function pointers to functions created at runtime
What I really really want to do in the end is:
class X
{
void action();
}
X* objects;
for(int i=0;i<0xFFFF;i++)
addresses[i] = & function(){ objects[i]->action() };
void someFunctionUnknownAtCompileTime()
{
}
void anotherFunctionUnknowAtCompileTime()
{
}
patch someFunctionUnknownAtCompileTime() with assembly to jump to function at addresses[0]
patch anotherFunctionUnknownAtCompileTime() with assembly to jump to function at addresses[1]
sth, I don't think your method will work because of them not being real functions but my bad in not explaining exactly what I want to do.
If I understand you correctly, you're trying to fill a buffer with machine code generated at runtime and get a function pointer to that code so that you can call it.
It is possible, but challenging. You can use reinterpret_cast<> to turn a data pointer into a function pointer, but you'll need to make sure that the memory you allocated for your buffer is flagged as executable by the operating system. That will involve a system call (LocalAlloc() on Windows iirc, can't remember on Unix) rather than a "plain vanilla" malloc/new call.
Assuming you've got an executable block of memory, you'll have to make sure that your machine code respects the calling convention indicated by the function pointer you create. That means pushing/popping the appropriate registers at the beginning of the function, etc.
But, once you've done that, you should be able to use your function pointer just like any other function.
It might be worth looking at an open source JVM (or Mono) to see how they do it. This is the essence of JIT compilation.
Here is an example I just hacked together:
int func1( int op )
{
printf( "func1 %d\n", op );
return 0;
}
int func2( int op )
{
printf( "func2 %d\n", op );
return 0;
}
typedef int (*fp)(int);
int main( int argc, char* argv[] )
{
fp funcs[2] = { func1, func2 };
int i;
for ( i = 0; i < 2; i++ )
{
(*funcs[i])(i);
}
}
The easiest way should be to create a bunch of boost::function objects:
#include <boost/bind.hpp>
#include <boost/function.hpp>
// ...
std::vector< boost::function<void ()> > functors;
for (int i=0; i<10; i++)
functors.push_back(boost::bind(callSomeFunction, i));
// call one of them:
functors[3]();
Note that the elements of the vector are not "real functions" but objects with an overloaded operator(). Usually this shouldn't be a disadvantage and actually be easier to handle than real function pointers.
You can do that simply by defining those functions by some arbitrary names in the global scope beforehand.
This is basically what is said above but modifying your code would look something like this:
std::vector<int (*) (int)> addresses;
for(int i=0;i<10;i++) {
addresses[i] = &myFunction;
}
I'm not horribly clear by what you mean when you say functions created at run time... I don't think you can create a function at run time, but you can assign what function pointers are put into your array/vector at run time. Keep in mind using this method all of your functions need to have the same signature (same return type and parameters).
You can't invoke a member function by itself without the this pointer. All instances of a class have the function stored in one location in memory. When you call p->Function() the value of p is stored somewhere (can't remember if its a register or stack) and that value is used as base offset to calculate locations of the member variables.
So this means you have to store the function pointer and the pointer to the object if you want to invoke a function on it. The general form for this would be something like this:
class MyClass {
void DoStuf();
};
//on the left hand side is a declaration of a member function in the class MyClass taking no parameters and returning void.
//on the right hand side we initialize the function pointer to DoStuff
void (MyClass::*pVoid)() = &MyClass::DoStuff;
MyClass* pMyClass = new MyClass();
//Here we have a pointer to MyClass and we call a function pointed to by pVoid.
pMyClass->pVoid();
As i understand the question, you are trying to create functions at runtime (just as we can do in Ruby). If that is the intention, i'm afraid that it is not possible in compiled languages like C++.
Note: If my understanding of question is not correct, please do not downvote :)