I am brand new to C and trying to better how understand memory is allocated and stored in class methods.
Lets say I have the following code:
#include <iostream>
using namespace std;
class ExampleClass {
public:
void SetStoredAttribute(int Argument);
int GetStoredAttribute(void);
private:
int StoredAttribute;
};
void ExampleClass::SetStoredAttribute(int Argument) {
StoredAttribute = Argument;
};
int ExampleClass::GetStoredAttribute(void) {
return StoredAttribute;
};
int main() {
ExampleClass Object;
Object.SetStoredAttribute(1);
cout << Object.GetStoredAttribute();
return 0;
};
What does C do with the argument once my SetStoredAttribute method is finished? Does it free that memory or do I need to do this manually?
CodePudding user response:
Function arguments, including those in member functions, always have automatic storage duration. They start to exist at the beginning of the function scope, and cease to exist at the end of the function scope, and the implementation deals with ensuring they are "allocated" and "deallocated".
On most platforms, this is implemented in two ways.
- Firstly by a stack, often called The Stack, because it is unique to the thread of execution, with a special purpose register in the CPU pointing to the top.
- Secondly, the arguments are directly assigned to registers in the CPU.