Reputation: 13
I hope my title is not misleading but I'd like to ask something which I don't know the correct title for.
At first, I'm not asking if a non-static member can be called through a static function. I know that the non-static member belongs to an instance of an object and that the static function belongs to the object itself. What I'd like to know is something different.
I developed a program during my master thesis which has a high consumption of RAM. I was wondering why because I'm using references all the time and only copy variables and objects if it is really necessary. However, checking memory allocation I noticed that my objects occupy 250kB of memory each, and I have a lot of them. I'd like to reduce that amount of memory by only instantiating what really needs to be instantiated.
Creating an instance of my object creates also an instance for each member function within my object. My question now is:
Since the functions don't change but the values do, can I declare a function as static so that it doesn't need to be copied all the time, but can still perform changes to the non-static member variables of an instance?
I hope it's clear what I'm asking for.
To emphasize my thought I want to give a little example.
Let's say I have the following code
class myObject(){
myType myVariable;
void getMyVariable(myType &typRef){
typRef = this->myVariable;
}
}
int main(){
myObject o1;
myObject o2;
myType t1;
myType t2;
o1.getMyVariable(t1);
o2.getMyVariable(t2);
std::cout << "Variable of object 1 is " << t1 << std::endl;
std::cout << "Variable of object 2 is " << t2 << std::endl;
}
I call the getMyVariable(myType &)
function twice. However it's sufficient to store it once since I does the same for every instance. The only thing that changes is the variable I get back.
Is there some keyword in c++ that allows to store a function in a static manner but dynamically holds the non-static members of an instance as exchangeable values to that function.
Hope it's clearer now what I'm looking for.
Upvotes: 0
Views: 260
Reputation: 171117
Creating an instance of my object, creates also an instance for each member function within my object.
No, it does not. Functions only exist once, in a part of memory dedicated to code, and are not associated to individual objects in any way.
Is there some keyword in c++ that allows to store a function in a static manner but dynamically holds the non-static members of an instance as exchangeable values to that function.
There is no keyword for this in C++, since it happens by default (and there's no way around it).
If your objects are too big, it's because they store too much data. Code is not part of an object's data layout and does not affect its size.
Upvotes: 4