when/why should i use static in c++? [closed] - c++

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 4 years ago.
Improve this question
I found Why/when should I declare a variable using static?, but the tags is about objective-c .
I can't make sure is there any difference in usage details between c++ and objective-c when you use static, so when/why should I use static in c++?

static has a couple of independent meanings, depending on context.
void f() { ... }
static void g() { ... }
Here, f has "external linkage", which means that its name is visible in other translation units. That is, in another source file you could have void f(); and then you could call the function f.
g, on the other hand, because it's marked static, has "internal linkage". You can call it from code in the same source file, but you cannot call it from another source file.
Same for objects:
int i = 3; // external linkage
static int j = 4; // internal linkage
And a small complication: you can define a static object inside a function.
void f() {
static int i = 3;
std::cout << i << '\n';
++i;
}
Here, i has no linkage. It's only visible inside the function. It gets initialized the first time the function is called (and doesn't get initialized at all if the function isn't called). So the first time that f is called it will write "3" to the console. On the second call it will write "4", etc. Understanding the behavior of objects with destructors is left as an exercise for the reader.
Inside a class definition it's completely different.
class C {
public:
void f();
static void g();
int i;
static int j;
};
Here, when you call f you must call it on an object of type C, and f can use data members of that object, that is, it can look at and change both i and j. When you call g there is no associated object. It's still a member of C, so it can look at and change j, because j, too, is not associated with any object. There's only one j, and it's shared by all objects of type C.

Related

why can't push static const member into vector? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
why can't push static const member into vector?
static const, static const constexpr, can't push into
static, non-static, and static const outside class, can push
sorry. I missed scope specifier , well I mean the situation that added specifier, can’t push static const member
struct A {
static const constexpr int sccv = 0;
static const int scv = 0;
static int sv = 0;
const int cv = 0;
};
int main () {
std::vector<int> vec;
vec.push_back(A::sccv); // error
vec.push_back(A::scv); // error
vec.push_back(A::sv); // pass
vec.push_back((new A())->cv); // pass
static const int sc = 0;
vec.push_back(sc); // pass
}
First I will assume that you wrote A:: at point-of-use, otherwise none of this code would have compiled.
When you "use" an object that has namespace-scope or is a class member, that is declared static, you must generally have a definition for it somewhere.
It might seem weird that a definition is needed even though you provided an initialiser at the point of declaration. That's because providing an initial value is only a small part of what a definition does. The more important part is giving the object a home, somewhere to live, specifying which compiled "module" will host the memory required for the object's existence. Like any object, your static member needs to be instantiated somewhere; the fact that it is lexically declared inside a class definition is a bit of a red herring.
So:
struct A {
static const constexpr int sccv = 0;
static const int scv = 0;
static int sv = 0;
const int cv = 0;
};
// In precisely one source file:
const constexpr int A::sccv;
const int A::scv;
int A::sv;
Now you won't get that "undefined reference" linker error any more.
There are some exceptions to the rule, and there are some scenarios in which compiler optimisations result in your program appearing to work regardless.

why we declare variable as a reference in private section of a class [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I know how useful it is to declare variable as a reference or pointer in a function, but I just wonder why we declare it as a reference in the private section of a class.
example
class DoSomething
{
private : int& t_; // why not just 'int t;'
};
How about if we declare the variable without reference, and define the object of a class as a pointer or reference? Is this not good practice?
If you declare the variable as int, its value would be "divorced" from the variable from which it has been initialized. If you keep it a reference, the variable would be "tracking" the variable with which it has been initialized:
class demoRef {
int &r;
public:
demoRef(int& x) : r(x) {}
void show() {cout << r << endl;}
};
class demoCopy {
int r;
public:
demoCopy(int& x) : r(x) {}
void show() {cout << r << endl;}
};
int main() {
int x = 123;
demoRef dRef(x);
demoCopy dCopy(x);
dRef.show();
dCopy.show();
x = 456;
dRef.show();
dCopy.show();
return 0;
}
This code produces the output below:
123
123
456
123
Demo on ideone.
Note: this is only an illustration of what you can do with a reference to an int. It is not meant to imply that you should do something like this without being extra careful, because a hidden reference like this makes your code harder to read.
There are many reasons you might have a reference member. An example from the standard library is the back_insert_iterator, which keeps a reference (or a pointer) to a container in order to call that container's push_back function.
Note that with any class like this, which stores a reference or pointer to another object, you need to take the same care as you would with a raw reference or pointer. That is, you need to be wary of dangling references, and ensure that you don't use the reference past the lifetime of the referent.
When you store a reference to a variable in a class, the outcome of changing the variable is:
You can change the variable in a member function of DoSomething and have that change be visible outside the class.
You can change the variable outside DoSomething and have that change be visible inside DoSomething.
The key question is: Where is it useful?
I have often found it useful in a functor that is passed to some of the functions in the standard library.
#BenjaminLindley already gave you a very good example of that.
I have often found it useful in Factory Patterns when a concrete Product is created using the data stored in a concrete Factory but the data is too expensive to copy.
I have used it in classes that implement a functional interface. These classes hold references to other data when:
3.1. The class needs to access to the data but it is too expensive to copy the data.
3.2. It makes no sense to copy the data or copying is prohibited by design (such as std::ofstream).
3.3. The class needs to update the data and make it visible to the calling code.

What does "redefinition" mean? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Is it true that redefinition mean that we're trying to define an entity which is already defined. This question appear from the following code example:
int a=5;
int main()
{
int a=3;//redefinition? I think no, because `int a` denote an entity different from the global "a"
}
and one more example:
int foo(){ return 1; }
int main()
{
int foo();
int a=foo();//Now a is 1
}
We can't define just declared foo() function inside the main() function body, but if we can will it be a redefinition?
Local variables might shadow global ones, that's what the :: scope resolution operator is for
#include <iostream>
using namespace std;
int a=5;
int main()
{
int a=3;
cout << a; // 3
cout << ::a; // 5
}
so no ODR problems here.
As for the second example the function declaration inside another function (when it doesn't get confused by the most-vexing-parse), I recommend this question: Is there a use for function declarations inside functions?
And: no, you can't redefine your function inside main(). You can redeclare it (even with different parameters, thus declaring a new function) but that doesn't mean you can define it so.
There's an excellent excerpt from the wiki page which I recommend to read:
In short, the ODR states that:
In any translation unit, a template, type, function, or object can
have no more than one definition. Some of these can have any number of
declarations. A definition provides an instance.
In the entire
program, an object or non-inline function cannot have more than one
definition; if an object or function is used, it must have exactly one
definition. You can declare an object or function that is never used,
in which case you don't have to provide a definition. In no event can
there be more than one definition.
Some things, like types, templates,
and extern inline functions, can be defined in more than one
translation unit. For a given entity, each definition must be the
same. Non-extern objects and functions in different translation units
are different entities, even if their names and types are the same.
Some violations of the ODR must be diagnosed by the compiler. Other
violations, particularly those that span translation units, are not
required to be diagnosed.1
No, when dealing with redefinition, it is important to remember SCOPE. It only applies for two variables with the same name that are defined in the SAME SCOPE
In example 1, the second a is LOCAL SCOPE and is local to the function. Therefore, that is the a that is viewed and referred to until you exit the function body
No. int a = foo(); or int a = 3; , inside main(), is a new variable that is also called a.
A redefinition is an attempt to redefine the same variable, e.g.:
int a = 5;
int a = 6;
Also
int foo();
is not a definition. It's a declaration. A function definition includes { }.
Redefinition is somewhat what leads to compiler-time error.
For example:
int a;
bool a;
or
void f();
int f;
In your case there wasn't compiler-time error. It was about name hiding, scope and resolving rules.
int a = 5;
{
int a = 6; //because of { } internal a is in other scope and can be defined without error
int b = a; //b == 6
}
int b = a; //b == 5
In the last case you have two diffrent "a", each in own scope of program.
In one point of program if you use a name such "a", there is only one entity that is behind this name. If compiler can't find the best match for "a" between diffrent variants you get redifinition and error.
The first one is not a redefinition due to different scopes, just like you thought.
The second one is a redeclaration, but it's ok to redeclare something any number of times you want, though the joke gets stale with repetition.
If you allow definition of functions inside functions, you get to write all the semantics, because there ain't such yet (aside from lambdas).
For someone who did so, look at the GCC C compiler, "nested functions" and "statement expressions".
Anyway, redefintion would be an error due to the One Definition Rule.

What kind of of object does this function return? [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
Imagine that you have a situation like this:
class className{
...
}
className func(){
className cl;
...
return cl;
}
int main(){
...
func();
}
What does the function func() return when you call it in the body of the program? A temporary copy of the object cl?
I don't understand this, since in the body of the function func() you can get the address &cl, but you get an error if you try to call &(func()) inside the function main().
Inside the function you are dealing with a so-called lvalue shortly speaking with an object which address is known because the object is defined explicitly.
The return value of the function is a temporary object (it is a so-called rvalue). Its address is not known. We do not know
where the compiler defined this object. So we may not apply operator & to a temporary object.
Another similar example
struct A
{
int x;
};
A f() { return A(); }
int main()
{
f().x = 10; // here the compiler will issue an error
}
This code shall not be compiled though for example MS VC++ 2010 will compile it due to either a bug or its language extension.:)

how to define a function in the scope of a class but not as a member function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
i do not mean friend function. I guess there is not a way to achieve this in C++ like any other languages. Am I right?
The background:
I have a helper function for a class A. I know there are a couple of options here
(1) to declare it in the same namespace as class A is in
(2) put it as a static function of class A.
I was just thinking if it is possible to do the following which is kind of the combination of the above two. i.e.,
I want that function to be right under the scope of A but not as a member function of class A.
I hope this is clearer now. Thanks a lot.
You mean a static member function.
class T
{
static void lol();
};
void T::lol()
{
/* ... */
}
int main()
{
T::lol();
}
This isn't really "in the scope of the class" any more than a free function would be, because the only thing that can really mean is access to member variables, and access to member variables requires an instance.
But this is the closest to what you've asked.
Do you mean like a static function?
class Foo
{
void memberFunction();
static void classFunction();
};
Foo foo;
foo.memberFunction(); // called as a member function
Foo::classFunction(); // called on the class, no object necessary
That's basically a function in the C++ "scope". I'm not sure what you mean by scope though. If you just mean namespace, then this is it.
You can declare it as a static function - that is a function that is defined against the class but which does not require access to any particular instance of that class's member variables:
static int foobar()...
Which is then called with
Foo::foobar();
If you want to limit the scope of the function so it can ONLY be called from inside the class, you can make it private much like any other member function.
If you wish, there's nothing stopping you from creating a standard member function and just not accessing any member variables...
The way I usually do this is to declare a function in the .c++ file with 'static' qualifier. Please realize that is different from the normal use of c++ 'static' functions.
If you declare in 'bar.c++' (not 'bar.h++'):
static void foo() {}
...it is a function which is not 'visible' outside its object file. I.e. a local helper function.
So to be precise:
bar.h++;
class bar
{
void f();
};
bar.c++;
#include "bar.h++"
static void foo() {}
void bar::f() { foo(); }
Cheers!
You can declare a nested class:
class A
{
class X
{
void helper(A object)
{
std::cout << object.member;
}
};
int member;
};
Here helper is a member function of class Y, not of class A. I am not sure how this helps you though.