Object and data members memory address confusion - c++

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?

"What's in a name? That which we call a rose By any other name would smell as sweet."
Concepts
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.
Explanation
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.

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.

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.

Related

Why C++ static data members are needed to define but non-static data members do not?

I am trying to understand the difference between the declaration & definition of static and non-static data members. Apology, if I am fundamentally miss understood concepts. Your explanations are highly appreciated.
Code Trying to understand
class A
{
public:
int ns; // declare non-static data member.
static int s; // declare static data member.
void foo();
};
int A::s; // define non-static data member.
// int A::ns; //This gives an error if defined.
void A::foo()
{
ns = 10;
s = 5; // if s is not defined this gives an error 'undefined reference'
}
When you declare something, you're telling the compiler that the name being declared exists and what kind of name it is (type, variable, function, etc.) The definition could be with the declaration (as with your class A) or be elsewhere—the compiler and linker will have to connect the two later.
The key point of a variable or function definition is that it tells the compiler and linker where this variable/function will live. If you have a variable, there needs to be a place in memory for it. If you have a function, there needs to be a place in the binary containing the function's instructions.
For non-static data members, the declaration is also the definition. That is, you're giving them a place to live¹. This place is within each instance of the class. Every time you make a new A object, it comes with an ns as part of it.
Static data members, on the other hand, have no associated object. Without a definition, you've got a situation where you have N instances of A all sharing the same s, but nowhere to put s. Therefore, C++ makes you choose one translation unit for it via a definition, most often the source file that acommpanies that header.
You could argue that the compiler should just pick one instance for it, but this won't work for various reasons, one being that you can use static data members before ever creating an instance, after the last instance is gone, or without having instances at all.
Now you might wonder why the compiler and linker still can't just figure it out on their own, and... that's actually pretty much what happens if you slap an inline on the variable or function. You can end up with multiple definitions, but only one will be chosen.
1: Giving them a place to live is a little beside the point here. All the compiler needs to know when it creates an object of that class is how much space to give it and which parts of that space are which data members. You could think of it as the compiler doing the definition part for you since there's only one place that data member could possibly live.
static members are essentially global variables with a special name and access rules tied to the class. Hence, they inherit all the problems for usual global variables. Namely, in the whole C++ program (which is the union of all translation units aka .cpp files) there should be exactly one definition of each global variable, no more.
You can think of "variable definition" as "the place which will allocate memory for the variable".
However, classes are typically defined in a header file (.h/.hpp/etc) which is included in multiple translation units. So it's up to the programmer to specify which translation unit actually defines the variable. Note that since C++17 we have the inline keyword which places this burden on a compiler, look for "inline variables". The naming is weird for historical reasons.
However, non-static members do not really exist until you create an instance of the class, i.e. an object. And it's the object lifetime and storage duration which define how each individual member is created/stored/destroyed. So there is no need to actually define them anywhere outside of the class.
static variables belongs to the class definition. non-static variables belong to the instances created with the class definition.
int main()
{
A::s = 5; // this is ok
A a;
a.ns = 5 // this is also ok
}

CreateTimerQueueTimer termination on WM_CLOSE [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I know the keyword in c has two usage:
modify variables
modify global variables
this usage limited the scope of global variable range from the point that defined to the end of the file.
modify local variables
this usage limited the scope of local variable in the function that defined, but also remained in the static area of memory
modify functions
this means can only invoke the function in the file it's defined.
and in c++, beside the usage in c, static also used to modify the data member and function member of class. This usage limited the member belong to the class instead of the objects of the class.
I want to know are there anything else usage of static in c/c++?
static is probably the most confusingly overloaded keyword in both C and C++. It means different things in different places.
Within functions, static is a storage class, denoting variables which exist for the lifetime of the programme. So saying
void f() {
static int i = 0;
}
says that the value of i will be preserved between calls to f(). Other storage classes are the default auto (but beware the change in meaning in C++11), extern, and register, plus thread_local in C11/C++11.
At file scope (or namespace scope in C++), static is a linkage specifier. Functions and variables marked static in this way have internal linkage, and so are local to the current translation unit. What this means is that a function like
static int f() {
return 3;
}
can only be referenced by other functions inside the same .c file. This usage of static was deprecated in C++03 in favour of unnamed namespaces. I read somewhere it was undeprecated again in C++11.
In C++, when applied to a member function or member variable of a class, it means that the function or variable does not need a class instance in order to be accessed. There is little different between "class static" member functions/variables and global functions/variable in terms of implementation, except that C++ class access specifiers apply to members.
One last one: in C99 (but not C++), static can be used within an array function parameter, like so:
void f(int a[static 4]) {
}
this specifies that the parameter a must by an integer array of size at least 4.
I think that's all of them, but let me know in the comments if there are any I've forgotten!
Static In the C language family, a static variable is one that exists for the lifetime of a compilation
unit (a source file or module). A static variable can be declared module-wide, and thus be
accessed by all functions defined within the same source file. Such a static variable cannot
be directly accessed from other modules, but inner-module API can pass pointers to static variables and
modify those through pointers. A static variable can also be declared within a function body, where the
usual scope rules apply. A static variable declared within a function is only initialized when
the module is initialized (typically when the application loads), and preserves its values over multiple
invocations of the function that contains the definition.
In C++, a static variable can also be a member of a class definition. Access to a static member
variable is governed by the standard access modifiers (private, public, protected), but all instances of
this class share the same static variable, and share the same value. Modifying the value of this variable
affects all objects of the class. VolatileThe volatile keyword is something all together different, and not in any way
an opposite to static. A static variable may or may not be declared volatile, just as a global or local variable
can be. The volatile keyword is a hint informing the compiler that the variable's value
might change without the compiler's knowledge. Therefore, the compiler's code optimizer cannot make assumptions
about the variable's current value, and must always (re-) read the variable's content.
In reference to c++ -> The static keyword can be used to declare variables, functions, class data members and class functions.
Here are the common usages in different scenarios ( ref from MSDN )
When you declare a variable or function at file scope (global and/or namespace scope), the static keyword specifies that the variable or function has internal linkage. When you declare a variable, the variable has static duration and the compiler initializes it to 0 unless you specify another value.
When you declare a variable in a function, the static keyword specifies that the variable retains its state between calls to that function.
When you declare a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. A static data member must be defined at file scope. An integral data member that you declare as const static can have an initializer.
When you declare a member function in a class declaration, the static keyword specifies that the function is shared by all instances of the class. A static member function cannot access an instance member because the function does not have an implicit this pointer. To access an instance member, declare the function with a parameter that is an instance pointer or reference.
You cannot declare the members of a union as static. However, a globally declared anonymous union must be explicitly declared static.
check following also:
The static keyword and its various uses in C++
static keyword usage

Differences between class and global variables

So, I was trying to make a list of the different types of variables and wanted to confirm if my classification was correct or not.
Three types, I say:
1.Static/Class
2.Instance
3.Global
I understand that global variables are declared outside the class definition but static variables must be declared (not necessarily instantiated) within the class definition. Are there any more important differences between the class and global variables?
A class is not synonymous with a static variable. Any variable can be declared static. Where it's declared will impact what it actually means.
What Does static Mean?
A class really isn't a variable type, it's how you define a new variable type. int is a type of variable, and Foo is a type of variable once you've defined it with the class keyword.
Instance really makes no sense. You have an instance of a variable, (e.g. an instance of an integer) but that's not a variable type.
In the terms of "types of variables", as you're looking at them, I would say there are two types: global and local. Static just has too many meanings to be included in that list.

what's the difference meaning of the keyword static between c and c++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I know the keyword in c has two usage:
modify variables
modify global variables
this usage limited the scope of global variable range from the point that defined to the end of the file.
modify local variables
this usage limited the scope of local variable in the function that defined, but also remained in the static area of memory
modify functions
this means can only invoke the function in the file it's defined.
and in c++, beside the usage in c, static also used to modify the data member and function member of class. This usage limited the member belong to the class instead of the objects of the class.
I want to know are there anything else usage of static in c/c++?
static is probably the most confusingly overloaded keyword in both C and C++. It means different things in different places.
Within functions, static is a storage class, denoting variables which exist for the lifetime of the programme. So saying
void f() {
static int i = 0;
}
says that the value of i will be preserved between calls to f(). Other storage classes are the default auto (but beware the change in meaning in C++11), extern, and register, plus thread_local in C11/C++11.
At file scope (or namespace scope in C++), static is a linkage specifier. Functions and variables marked static in this way have internal linkage, and so are local to the current translation unit. What this means is that a function like
static int f() {
return 3;
}
can only be referenced by other functions inside the same .c file. This usage of static was deprecated in C++03 in favour of unnamed namespaces. I read somewhere it was undeprecated again in C++11.
In C++, when applied to a member function or member variable of a class, it means that the function or variable does not need a class instance in order to be accessed. There is little different between "class static" member functions/variables and global functions/variable in terms of implementation, except that C++ class access specifiers apply to members.
One last one: in C99 (but not C++), static can be used within an array function parameter, like so:
void f(int a[static 4]) {
}
this specifies that the parameter a must by an integer array of size at least 4.
I think that's all of them, but let me know in the comments if there are any I've forgotten!
Static In the C language family, a static variable is one that exists for the lifetime of a compilation
unit (a source file or module). A static variable can be declared module-wide, and thus be
accessed by all functions defined within the same source file. Such a static variable cannot
be directly accessed from other modules, but inner-module API can pass pointers to static variables and
modify those through pointers. A static variable can also be declared within a function body, where the
usual scope rules apply. A static variable declared within a function is only initialized when
the module is initialized (typically when the application loads), and preserves its values over multiple
invocations of the function that contains the definition.
In C++, a static variable can also be a member of a class definition. Access to a static member
variable is governed by the standard access modifiers (private, public, protected), but all instances of
this class share the same static variable, and share the same value. Modifying the value of this variable
affects all objects of the class. VolatileThe volatile keyword is something all together different, and not in any way
an opposite to static. A static variable may or may not be declared volatile, just as a global or local variable
can be. The volatile keyword is a hint informing the compiler that the variable's value
might change without the compiler's knowledge. Therefore, the compiler's code optimizer cannot make assumptions
about the variable's current value, and must always (re-) read the variable's content.
In reference to c++ -> The static keyword can be used to declare variables, functions, class data members and class functions.
Here are the common usages in different scenarios ( ref from MSDN )
When you declare a variable or function at file scope (global and/or namespace scope), the static keyword specifies that the variable or function has internal linkage. When you declare a variable, the variable has static duration and the compiler initializes it to 0 unless you specify another value.
When you declare a variable in a function, the static keyword specifies that the variable retains its state between calls to that function.
When you declare a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. A static data member must be defined at file scope. An integral data member that you declare as const static can have an initializer.
When you declare a member function in a class declaration, the static keyword specifies that the function is shared by all instances of the class. A static member function cannot access an instance member because the function does not have an implicit this pointer. To access an instance member, declare the function with a parameter that is an instance pointer or reference.
You cannot declare the members of a union as static. However, a globally declared anonymous union must be explicitly declared static.
check following also:
The static keyword and its various uses in C++
static keyword usage

Difference between static in C and static in C++??

What is the difference between the static keyword in C and C++?
The static keyword serves the same purposes in C and C++.
When used at file level (outside of a function), it sets the visibility of the item it's applied to. Static items are not visible outside of their compilation unit (e.g., to the linker). Their duration is the same as the duration of the program.
These file-level items (functions and data) should be static unless there's a specific need to access them from outside (and there's almost never a need to give direct access to data since that breaks the central tenet of encapsulation).
If (as your comment to the question indicates) this is the only use of static you're concerned with then, no, there is no difference between C and C++.
When used within a function, it sets the duration of the item. Again, the duration is the same as the program and the item continues to exist between invocations of that function.
It does not affect the visibility of that item since it's visible only within the function. An example is a random number generator that needs to keep its seed value between invocations but doesn't want that value visible to other functions.
C++ has one more use, static within a class. When used there, it becomes a single class variable that's common across all objects of that class. One classic example is to store the number of objects that have been instantiated for a given class.
As others have pointed out, the use of file-level static has been deprecated in favour of unnamed namespaces. However, I believe it'll be a cold day in a certain warm place before it's actually removed from the language - there's just too much code using it at the moment. And ISO C have only just gotten around to removing gets() despite the amount of time we've all known it was a dangerous function.
And even though it's deprecated, that doesn't change its semantics now.
The use of static at the file scope to restrict access to the current translation unit is deprecated in C++, but still acceptable in C.
Instead, use an unnamed namespace
namespace
{
int file_scope_x;
}
Variables declared this way are only available within the file, just as if they were declared static.
The main reason for the deprecation is to remove one of the several overloaded meanings of the static keyword.
Originally, it meant that the variable, such as in a function, would be given storage for the lifetime of the program in an area for such variables, and not stored on the stack as is usual for function local variables.
Then the keyword was overloaded to apply to file scope linkage. It's not desirable to make up new keywords as needed, because they might break existing code. So this one was used again with a different meaning without causing conflicts, because a variable declared as static can't be both inside a function and at the top level, and functions didn't have the modifier before. (The storage connotation is totally lost when referring to functions, as they are not stored anywhere.)
When classes came along in C++ (and in Java and C#) the keyword was used yet again, but the meaning is at least closer to the original intention. Variables declared this way are stored in a global area, as opposed to on the stack as for function variables, or on the heap as for object members. Because variables cannot be both at the top level and inside a class definition, extra meaning can be unambiguously attached to class variables. They can only be referenced via the class name or from within an object of that class.
It has the same meaning in both languages.
But C++ adds classes. In the context of a class (and thus a struct) it has the extra meaning of making the method/variable class members rather members of the object.
class Plop
{
static int x; // This is a member of the class not an instance.
public:
static int getX() // method is a member of the class.
{
return x;
}
};
int Plop::x = 5;
Note that the use of static to mean "file scope" (aka namespace scope) is only deoprecated by the C++ Standard for objects, not for functions. In other words,:
// foo.cpp
static int x = 0; // deprecated
static int f() { return 1; } // not deprecated
To quote Annex D of the Standard:
The use of the static keyword is
deprecated when declaring objects in
namespace scope.
You can not declare a static variable inside structure in C... But allowed in Cpp with the help of scope resolution operator.
Also in Cpp static function can access only static variables but in C static function can have static and non static variables...😊