I'm trying make number guessing game with qt creator. I need to access a variable from another function. I was able to do that on python by adding "self." to beggining of variable but I can't do it on C++. Here's a sample what I am trying to do:
void function1()
{
int i;
}
void function2()
{
I need to access i here.
}
Thanks for help.
You could use pointers, classes or global variable ( I'd recommend pointers or a class tho)
void f1(int *iPtr)
{
cout << "value= " <<*iPtr << endl;
}
void f2(int *iPtr)
{
*iPtr = *iPtr + 5; // access ( modify ) variable here
cout << "after addition = " << *iPtr << endl;
}
int main()
{
int i = 5;
int *iPtr;
iPtr = &i; // point pointer to location of i
f1(iPtr);
f2(iPtr);
// after f1() value of i == 5, after f2() value of i == 10
}
I believe the equivalent behavior in C++ would be a member variable.
If you're not already, I'd suggest using a class. So, in your header file define it something like this:
class MyClass {
public:
void function1();
void function2();
private:
int i;
};
If you're not using C++ classes, then you can define "i" in the header file but that will make it global - in essense. And, probably not the best practice.
It is not possible to access a variable from another function since they exist only on the stack and they are destroyed when the function exits. Use a global variable.
You could declare i as a global variable and just assign it the random number once you have chosen it. That way you could still generate a random number and use it in another function.
int i;
void function1()
{
int randNum;
// get random number here
i = randNum;
}
void function2()
{
// do stuff with i here
}
Related
void testing(){
cout << it << endl;
};
int main(){
int it = 99;
testing();
return 0;
}
This is probably a real rookie and basic question but how can i access the variable it within the function testing without passing it as an argument?
Or is the scope a function can access defined by where it is defined.
for example, testing defined in global scope, cannot access main function scope?
You can access the variable making it a global variable.
int it;
void testing(){
cout << it << endl;
};
int main(){
it = 99;
testing();
return 0;
}
But you should avoid using global variables. Since every function can access these it can be hard to figure out which functions actually access and modify these variables.
You should prefer passing variables between functions as it makes you code easier to read and you can avoid errors like unwanted value overrides.
Can someone explain me the difference between own variable of the class and inherited variable?
For example in this code:
class First
{
public:
int test;
First::First()
{
test = 5;
}
};
class Second : public First
{
public:
void setTest(int test)
{
Second::test = test;
}
int Second::GetTestFirst()
{
return First::test;
}
int Second::GetTestSecond()
{
return Second::test;
}
};
int main()
{
int input;
Second * sec = new Second;
cin >> input;
sec->setTest(input); //for example 15
std::cout << sec->GetTestFirst();
std::cout << sec->GetTestSecond();
return 0;
}
What is the difference between output of GetTestFirst() and GetTestSecond()? Is it pointing to same memory block? And if it is the same thing, which one is better to use?
There is no difference - a Second object has only one test member, inherited from First. So saying
return First::test;
is redundant - you can just use
return test
(without this as the other answer states - this is not necessary as well). Also you should not use
Second::GetTestFirst()
and similar. The compiler knows perfectly that it is compiling Second.
GetTestFirst()
is enough. As far as I can see all First:: and Second:: in your code are not necessary. And the last observation: in C++ you should not use dynamic memory unless you need to. Instead of
Second * sec = new Second;
you should use
Second sec;
and . instead of -> later.
GetTestFirst() and GetTestSecond() does the same thing since test variable only defined inside the base class. Proper way to address that variable would be using this keyword;
return this->test;
This is just the outline of the code I am trying.please help me !
void surfaceintensity(int xpos,int ypos ,int zpos)
{
x[1]=xpos;
x[2]=ypos;
x[3]=zpos;
}
Suppose I have an object t1 and I have sent values to the function surface intensity as:
t1.surfaceintensity(10,20,30)
If i do it above mentioned way then,will the values of
x[1]=10;
x[2]=20;
x[3]=30;
If not how can I assign these values to the array x[]?
If I understand you right, I think our code does what you expect. However you should use array index 0..2 instead of 1..3!
The way I understand your question, you have a class (let's call it MyClass) which has a member function surfaceintensity(). This member function assigns some values to the elements of an array x which is also a member of your class.
You're unsure if assigning values to that array from inside the member function will actually change the array of the instance its called upon. If that is the case, then look at the following example (just copy/paste it, it should compile):
#include <iostream>
class MyClass
{
public:
MyClass()
{
x[0] = 0;
x[1] = 0;
x[2] = 0;
}
void surfaceintensity(int xpos,int ypos ,int zpos)
{
x[0]=xpos;
x[1]=ypos;
x[2]=zpos;
}
void print()
{
std::cout << x[0] << "/" << x[1] << "/" << x[2] << std::endl;
}
private:
int x[3];
};
int main()
{
MyClass t1;
t1.print();
t1.surfaceintensity(10,20,30);
t1.print();
return 0;
}
This will print
0/0/0
10/20/30
This demonstrates that the answer to your question is: yes, assigning values to member variables does change the internal state of the object.
I hope this was what you we're asking. If not, please edit your question and clarify.
For example:
#include <iostream>
#include <deque>
int func(int a){
std::deque<int> obj;
obj.push_back(a);
for(std::deque<int>::iterator it = obj.begin(); it!=obj.end();++it)
std::cout << *it << '\n';
return 0;
}
int main()
{
int x=2;
func(x);
func(x);
}
output is :
2
2
so its mean that deque object destroy after reach end scope of func. And i cant do nothing with this, except return value or add to global scope? No way to change behavior of this object with adding static to him or static pointer or something else? I mean that with pure C++ its look like :
int func(int a){
static int *p = new int;
}
and value will be store between function calls but how to do same with stl containers i don't know.
If you really want it to be static, make it so:
static std::deque<int> obj;
although this is probably a bad idea: conceptually, you have hidden state in the program, and practically, there's a possibility of accessing the object after it's been destroyed. (You can fudge around the lifetime issues by using dynamic allocation and leaking the object, as demonstrated in Drax's answer, if you really want to go down this particular road of pain).
Better would be to encapsulate the state in a class. Then you can control exactly when it's created and destroyed, and have more than one instance if you like.
class thing {
public:
int func(int a) {
obj.push_back(a);
// and print it
}
private:
std::deque<int> obj;
};
int main() {
thing t;
t.func(2); // 2
t.func(3); // 2 3
}
If you want to remember data between function calls, store it elsewhere, or as a last resort make it static.
So, either go with Mike Seymour's answer to make it a member of a class, or hold onto it in main, and pass it to the function, making sure you pass by reference if you wish to change it:
int func(int a, std::deque<int> & obj){
//.. as you were
}
From main, make the data and pass it in:
int main()
{
int x=2;
std::deque<int> obj;
func(x, obj);
func(x, obj);
}
Simply :
int func(int a){
static std::deque<int>* obj = new std::deque<int>;
obj->push_back(a);
for(std::deque<int>::iterator it = obj->begin(); it!=obj->end();++it)
std::cout << *it << '\n';
}
But i'm not sure that's a good idea :)
Is there a way to initialize a variable in a function and save its value for next call of function?
I'm making application in qt and i have one function connected with a signal. I want an variable in that function to change after the other one reaches its goal. Here is the body of that function:
void objekt::advance(int phase)
{
if(!phase) return;
QPointF location = this->pos();
if (int(location.x())==200 || int(location.x())==-200)
{
smijer=-smijer;
}
setPos(mapToParent(smijer,0));
}
I defined the smijer variable as static int. But i dont'know how to initialize it only once, when program starts, and how to keep its new value after each call of the function.
Your answer is in your question basically. Static variables (either a class member or local variable of a function) is initialized only once where it is terminated. For example;
#include <iostream>
int foo () {
static int sVar = 5;
sVar++;
return sVar;
}
using namespace std;
int main () {
int iter = 0;
do {
cout << "Svar :" foo() << endl;
iter++;
}while (iter < 3);
}
if you write a program like that it will print out Svar values just like;
Svar :6
Svar :7
Svar :8
So as you see although we call foo function three times the initialization of a static varible is done only once.
Why am I being downvoted? He wants to change a variable and preserve the states after function calls. (He doesn't specify whether the variable is a member of the class or anything, so I'm assuming it's not. I'll change my answer if he clarifies and states his question less ambiguously.)
You're going about this wrong. To keep a variable after a function's scope ends, you have to allocate it on the heap rather than the stack. You can use new or malloc to do this, but you also have to free this memory with delete and free, in that order.
With new and delete:
#include <iostream>
void modify(int * p){
(*p)++;
}
int main(void){
int * pointer = new int;
*pointer = 5;
std::cout << *pointer << std::endl;
modify(pointer);
std::cout << *pointer << std::endl;
delete pointer;
return 0;
}
And with malloc and free:
#include <iostream>
#include <cstdlib>
void modify(int * p){
(*p)++;
}
int main(void){
int * pointer = (int*)malloc(sizeof(int)); //DO NOT CAST IN C
*pointer = 5;
std::cout << *pointer << std::endl;
modify(pointer);
std::cout << *pointer << std::endl;
free(pointer);
return 0;
}
new does provide facilities for deleting arrays quickly and is better overall for normal use C++.
If smijer is a member of class objekt, then do it like this:
objekt.h:
class objekt
{
...
static int smijer;
...
};
objekt.cpp
int objekt::smijer = YOUR_INITIALIZATION_VALUE;
On the other hand, if you want/need smijer to be a global variable, then do it like this:
globals.h:
extern int smijer;
globals.cpp //Or another .cpp file
int smijer = YOUR_INITIALIZATION_VALUE;
Although in this case I'd stick it in a namespace. In this case it isn't declared static but it does have the lifetime of your program.
Declare the variable as static inside the function and the valued will be remembered. You don't need to initialize it. But you can if you want to.