Reputation: 96
When we declare a data member of the same name inside a class as well as the function parameter within the same class, we use "this->" to point to the memory location of the class. What I am confused at is: say we declare a data member called "meloncolor" and then declare within the class a function parameter of the same name, like say:
class fruitcolor{
public:
string meloncolor;
void changefruitcolor(string meloncolor)
{ this-> meloncolor = meloncolor }
};
Say our object is stored at memory location 0xblahblahblah, so both "moloncolor" data members/variables should be at the same location? If so, how does the program/computer distinguishes each other after pointing to the class address using "this->" if they are stored at the same location?
Upvotes: 1
Views: 337
Reputation: 78
As you already know there are different types/scope of variables, compiler decides where and how to store them based on their types/scope. For your understanding i am dividing your problem into two point hope you can understand.
1: Instance variables: These variables are store in the heap memory. Your "public: string meloncolor;" is class level variable also known as instance.
2: Local variables: This type of variables are store on the stack, your "void changefruitcolor(string meloncolor)" is a local variable.
So, they both are stored at the different place in the memory, may have different values at the same time.
Upvotes: 1
Reputation: 63737
"What's in a name? That which we call a rose By any other name would smell as sweet."
Object do not have name. An object is a location in memory of a certain type, and a size conforming to the type, having a value (assigned / unassigned) possibly referred by an identifier.
Namespace is a grouping of symbols / identifiers which provide a level of direction to specific identifiers, thereby making it possible to differentiate among identical identifiers. Namespace provides a mechanism wherein identifiers with same symbolic name can cohabitate (coexist) without conflicting/ overriding/ shadowing.
In your particular cases, the parameter meloncolor and the instance member meloncolor refers to different objects with same symbolic name but in different namespace. Local variables and parameters of a function have function level scope and have a local namespace. Any variable/identifier with a name conflict with a global or class/struct namespace would be overridden. To make explicit differentiation we need to use a scope level resolution. For instance variable in C++, we use the member selection operator .
for name resolution of a symbol defined in the current object instance.
Upvotes: 1
Reputation: 9602
so both "moloncolor" data members/variables should be at the same location?
No. One is stored on the class instance and one is stored on function call stack. Using this->
fully qualifies the member variable to disambiguate its name from the parameter's name.
Upvotes: 1