updating variable between functions in c++ - c++

My main program is to generate a random number to create movement of a object in a 2 dimensional array and to keep track of it.
one of my function void current_row(int row){position = row}; keeps track of the current row of the object.
since the variable is not global. i am finding problems calling the current location and updating it to the next movement. this is how the other function may look like:
void movement (){
int row;
row = current_row();
/*
* Here is the problem i'm having. This may well be
* a third function which has the same information
* as my first function. But still how do I access
* once without modifying it and access it
* again to update it?
*/
// call another function that creates new row.
// update that info to the row
}
i am new to c++.

Use an instance variable to keep track of it. That's why instance variables exist: To hold their values between function calls.

In case it's an OOP environment (as C++ tag implies), some class should declare int row as a class member (including a getter and a setter as methods).
Another option is declaring the variable at the head of the main() part of the program and call functions with row as a function parameter.
void movement(int row)
{
}
You can consider the parameter be passed by reference if you are intending to change it, otherwise it would be better declaring it const inside the function parameter declaration. If part of the answer sounds unfamiliar to you I would suggest reading through :
What's the difference between passing by reference vs. passing by value?

Related

Beginner question about modifying class function call with passed variable

Need help modifying code. I am new to classes.
Original code calls a class function and passes in a value derived from calling another class function and then adding 1 to it. I want to simply pass in a variable value.
I figured out how to cheat by multiplying the returned value by 0 and then adding to that the value I am trying to pass in. This works but I want to do it right by only passing in the desired value:
Modified code:
// sets the temp to a specific value
void SmartBbq::setProbeAlarm(int probeIndex, float alarmTemp) {
_smartProbes[probeIndex]->setAlarmTemp(_smartProbes[probeIndex]->getAlarmTemp() * 0 + alarmTemp);
}
Original code:
// increases temp by 1 degree
void SmartBbq::up() {
_smartProbes[_active]->setAlarmTemp(_smartProbes[_active]->getAlarmTemp() + 1);
}
If this is not enough information I can include the class definitions. I realize the class definitions may need to be modified as well to accept the incoming argument. I have made changes there that might be correct but I can't figure out how to properly call the class function with argument.
Adding to my confusion is that it appears one class function calls another adding layers to the complexity.

C++ global extern constant defined at runtime available across multiple source files

I have an integer constant that is to be defined at runtime. This constant needs to be available globally and across multiple source files. I currently have the following simplified situation:
ClassA.h declares extern const int someConstant;
ClassA.cpp uses someConstant at some point.
Constants.h declares extern const int someConstant;
main.cpp includes ClassA.h and Constants.h, declares const int someConstant, and at some point during main() tries to initialize someConstant to the real value during runtime.
This works flawlessly with a char * constant that I use to have the name of the program globally available across all files, and it's declared and defined exactly like the one I'm trying to declare and define here but I can't get it to work with an int.
I get first an error: uninitialized const ‘someConstant’ [-fpermissive] at the line I'm declaring it in main.cpp, and later on I get an error: assignment of read-only variable ‘someConstant’ which I presume is because someConstant is getting default initialized to begin with.
Is there a way to do what I'm trying to achieve here? Thanks in advance!
EDIT (per request from #WhozCraig): Believe me: it is constant. The reason I'm not posting MCVE is because of three reasons: this is an assignment, the source is in Spanish, and because I really wanted to keep the question as general (and reusable) as possible. I started out writing the example and midway it striked me as not the clearest question. I'll try to explain again.
I'm asked to build a program that creates a process that in turn spawns two children (those in turn will spawn two more each, and so on). The program takes as single argument the number of generations it will have to spawn. Essentially creating sort of a binary tree of processes. Each process has to provide information about himself, his parent, the relationship with the original process, and his children (if any).
So, in the example above, ClassA is really a class containing information about the process (PID, PPID, children's PIDs, degree of relation with the original process, etc). For each fork I create a new instance of this class, so I can "save" this information and print it on screen.
When I'm defining the relationship with the original process, there's a single point in which I need to know the argument used when calling the program to check if this process has no children (to change the output of that particular process). That's the constant I need from main: the number of generations to be spawned, the "deepness" of the tree.
EDIT 2: I'll have to apologize, it's been a long day and I wasn't thinking straight. I switched the sources from C to C++ just to use some OO features and completely forgot to think inside of the OO paradigm. I just realized while I was explaining this that I might solve this with a static/class variable inside my class (initialized with the original process), it might not be constant (although semantically it is) but it should work, right? Moreover I also realized I could just initialize the children of the last generation with some impossible PID value and use that to check if it is the last generation.
Sorry guys and thank you for your help: it seems the question was valid but it was the wrong question to ask all along. New mantra: walk off the computer and relax.
But just to recap and to stay on point, it is absolutely impossible to create a global constant that would be defined at runtime in C++, like #Jerry101 says?
In C/C++, a const is defined at compile time. It cannot be set at runtime.
The reason you can set a const char *xyz; at runtime is this declares a non-const pointer to a const char. Tricky language.
So if you want an int that can be determined in main() and not changed afterwards, you can write a getter int xyz() that returns a static value that gets initialized in main() or in the getter.
(BTW, it's not a good idea to declare the same extern variable in more than one header file.)
As others have mentioned, your variable is far from being constant if you set it only at run-time. You cannot "travel back in time" and include a value gained during the program's execution into the program itself before it is being built.
What you can still do, of course, is to define which components of your program have which kind of access (read or write) to your variable.
If I were you, I would turn the global variable into a static member variable of a class with a public getter function and private setter function. Declare the code which needs to set the value as a friend.
class SomeConstant
{
public:
static int get()
{
return someConstant;
}
private:
friend int main(); // this should probably not be `main` in real code
static void set(int value)
{
someConstant = value;
}
static int someConstant = 0;
};
In main:
int main()
{
SomeConstant::set(123);
}
Anywhere else:
void f()
{
int i = SomeConstant::get();
}
You can further hide the class with some syntactic sugar:
int someConstant()
{
return SomeConstant::get();
}
// ...
void f()
{
int i = someConstant();
}
Finally, add some error checking to make sure you notice if you try to access the value before it is set:
class SomeConstant
{
public:
static int get()
{
assert(valueSet);
return someConstant;
}
private:
friend int main(); // this should probably not be `main` in real code
static void set(int value)
{
someConstant = value;
valueSet = true;
}
static bool valueSet = false;
static int someConstant = 0;
};
As far as your edit is concerned:
Nothing of this has anything to do with "OO". Object-oriented programming is about virtual functions, and I don't see how your problem is related to virtual functions.
char * - means ur creating a pointer to char datatype.
int - on other hand creates a variable. u cant declare a const variable without value so i suggest u create a int * and use it in place of int. and if u are passing it into functions make it as const
eg: int *myconstant=&xyz;
....
my_function(myconstant);
}
//function decleration
void my_function(const int* myconst)
{
....
}
const qualifier means variable must initialized in declaration point. If you are trying to change her value at runtime, you get UB.
Well, the use of const in C++ is for the compiler to know the value of a variable at compile time, so that it can perform value substitution(much like #define but much more better) whenever it encounters the variable. So you must always assign a value to a const when u define it, except when you are making an explicit declaration using extern. You can use a local int to receive the real value at run time and then you can define and initialize a const int with that local int value.
int l_int;
cout<<"Enter an int";
cin>>l_int;
const int constNum = l_int;

How to create method which will know that its instance is in matrix of another class

I'm an absolute beginner in OOP (and C++). Trying to teach myself using resources my university offers for students of higher years, and a bunch of internet stuff I can find to clear things up.
I know basic things about OOP - I get the whole point of abstracting stuff into classes and using them to create objects, I know how inheritance works (at least, probably the basics), I know how to create operator functions (although as far as I can see that only helps in code readability in a sense that it becomes more standard, more language like), templates, and stuff like that.
So I've tried my first "project": to code Minesweeper (in command line, I never created a GUI before). Took me a few hours to create the program, and it works as desired, but I feel like I'm missing a huge point of OOP in there.
I've got a class "Field" with two attributes, a Boolean mine and a character forShow. I've defined the default constructor for it to initialize an instance as an empty field (mine is false), and forShowis . (indicating a not yet opened filed). I've got some simple inline functions such as isMine, addMine, removeMine, setForShow, getForShow, etc.
Then I've got the class Minesweeper. Its attributes are numberOfColumns, ~ofRows, numberOfMines, a pointer ptrGrid of type Mine*, and numberOfOpenedFields. I've got some obvious methods such as generateGrid, printGrid, printMines (for testing purposes).
The main thingy about it is a function openFiled which writes the number of mines surrounding the opened field, and another function clickField which recursively calls itself for surrounding fields if the field which is currently being opened has 0 neighbor mines. However, those two functions take an argument -- the index of the field in question. That kinda misses the point of OOP, if I understand it correctly.
For example, to call the function for the field right to the current one, I have to call it with argument i+1. The moment I noticed this, I wanted to make a function in my Field class which would return a pointer to the number right to it... but for the class Field itself, there is no matrix, so I can't do it!
Is it even possible to do it, is it too hard for my current knowledge? Or is there another more OOP-ish way to implement it?
TLDR version:
It's a noob's implemetation of Minesweeper game using C++. I got a class Minesweeper and Field. Minesweeper has a pointer to matrix of Fields, but the navigation through fields (going one up, down, wherever) doesn't seem OOP-ishly.
I want to do something like the following:
game->(ptrMatrix + i)->field.down().open(); // this
game->(ptrMatrix + i + game.numberOfColumns).open(); // instead of this
game->(ptrMatrix + i)->field.up().right().open(); // this
game->(ptrMatrix + i + 1 - game.numberOfColumns).open(); // instead of this
There are a couple of ways that you could do this in an OOP-ish manner. #Peter Schneider has provided one such way: have each cell know about its neighbours.
The real root of the problem is that you're using a dictionary (mapping exact coordinates to objects), when you want both dictionary-style lookups as well as neighbouring lookups. I personally wouldn't use "plain" OOP in this situation, I'd use templates.
/* Wrapper class. Instead of passing around (x,y) pairs everywhere as two
separate arguments, make this into a single index. */
class Position {
private:
int m_x, m_y;
public:
Position(int x, int y) : m_x(x), m_y(y) {}
// Getters and setters -- what could possibly be more OOPy?
int x() const { return m_x; }
int y() const { return m_y; }
};
// Stubbed, but these are the objects that we're querying for.
class Field {
public:
// don't have to use an operator here, in fact you probably shouldn't . . .
// ... I just did it because I felt like it. No justification here, move along.
operator Position() const {
// ... however you want to get the position
// Probably want the Fields to "know" their own location.
return Position(-1,-1);
}
};
// This is another kind of query. For obvious reasons, we want to be able to query for
// fields by Position (the user clicked on some grid), but we also would like to look
// things up by relative position (is the cell to the lower left revealed/a mine?)
// This represents a Position with respect to a new origin (a Field).
class RelativePosition {
private:
Field *m_to;
int m_xd, m_yd;
public:
RelativePosition(Field *to, int xd, int yd) : m_to(to), m_xd(xd),
m_yd(yd) {}
Field *to() const { return m_to; }
int xd() const { return m_xd; }
int yd() const { return m_yd; }
};
// The ultimate storage/owner of all Fields, that will be manipulated externally by
// querying its contents.
class Minefield {
private:
Field **m_field;
public:
Minefield(int w, int h) {
m_field = new Field*[w];
for(int x = 0; x < w; x ++) {
m_field[w] = new Field[h];
}
}
~Minefield() {
// cleanup
}
Field *get(int x, int y) const {
// TODO: check bounds etc.
// NOTE: equivalent to &m_field[x][y], but cleaner IMO.
return m_field[x] + y;
}
};
// The Query class! This is where the interesting stuff happens.
class Query {
public:
// Generic function that will be instantiated in a bit.
template<typename Param>
static Field *lookup(const Minefield &field, const Param &param);
};
// This one's straightforwards . . .
template<>
Field *Query::lookup<Position>(const Minefield &field, const Position &pos) {
return field.get(pos.x(), pos.y());
}
// This one, on the other hand, needs some precomputation.
template<>
Field *Query::lookup<RelativePosition>(const Minefield &field,
const RelativePosition &pos) {
Position base = *pos.to();
return field.get(
base.x() + pos.xd(),
base.y() + pos.yd());
}
int main() {
Minefield field(5,5);
Field *f1 = Query::lookup(field, Position(1,1));
Field *f0 = Query::lookup(field, RelativePosition(f1, -1, -1));
return 0;
}
There are a couple of reasons why you might want to do it this way, even if it is complicated.
Decoupling the whole "get by position" idea from the "get neighbour" idea. As mentioned, these are fundamentally different, so expose a different interface.
Doing it in this manner gives you the opportunity to expand later with more Query types in a straightforwards fashion.
You get the advantage of being able to "store" a Query for later use. Perhaps to be executed in a different thread if it's a really expensive query, or in an event loop to be processed after other events, or . . . lots of reasons why you might want to do this.
You end up with something like this: (C++11 ahead, be warned!)
std::function<Field *()> f = std::bind(Query::lookup<RelativePosition>,
field, RelativePosition(f1, -1, -1));
. . . wait, what?
Well, what we essentially want to do here is "delay" an execution of Query::lookup(field, RelativePosition(f1, -1, -1)) for later. Or, rather, we want to "set up" such a call, but not actually execute it.
Let's start with f. What is f? Well, by staring at the type signature, it appears to be a function of some sort, with signature Field *(). How can a variable be a function? Well, it's actually more like a function pointer. (There are good reasons why not to call it a function pointer, but that's getting ahead of ourselves here.)
In fact, f can be assigned to anything that, when called, produces a Field * -- not just a function. If you overload the operator () on a class, that's a perfectly valid thing for it to accept as well.
Why do we want to produce a Field * with no arguments? Well, that's an execution of the query, isn't it? But the function Query::lookup<RelativePosition> takes two arguments, right?
That's where std::bind comes in. std::bind essentially takes an n-argument function and turns it into an m-argument function, with m <= n. So the std::bind call takes in a two-place function (in this case), and then fixes its first two arguments, leaving us with . . .
. . . a zero-argument function, that returns a Field *.
And so we can pass around this "function pointer" to a different thread to be executed there, store it for later use, or even just repeatedly call it for kicks, and if the Position of Fields was to magically change for some reason (not applicable in this situation), the result of calling f() will dynamically update.
So now that I've turned a 2D array lookup into a mess of templates . . . we have to ask a question: is it worth it? I know this is a learning exercise and all, but my response: sometimes, an array is really just an array.
You can link the four neighbours to the cell via pointers or references. That would likely happen after the playing field has been created. Whether that's good or bad design I'm not sure (I see the same charme though that you see). For large fields it would increase the memory footprint substantially, because a cell probably doesn't hold that much data besides these pointers:
class Cell
{
// "real" data
Cell *left, *right, *upper, *lower;
// and diagonals? Perhaps name them N, NE, E, SE, S...
};
void init()
{
// allocate etc...
// pseudo code
foreach r: row
{
foreach c: column
{
// bounds check ok
cells[r][c].upper = &cells[r-1][c];
cells[r][c].left = &cells[r][c-1];
// etc.
}
}
// other stuff
}

C++ - Fastest way to reinterpret this data

Suppose I have the following class:
class DX11ConstantBuffer
{
public:
ID3D11Buffer *pData;
};
I receive an array of this class in a function:
DX11ConstantBuffer **pp
My wrapper (DX11ConstantBuffer) contains a pointer to ID3D11Buffer. The following function:
pDevcon->VSSetConstantBuffers
requires a pointer to an array of ID3D11Buffers,
ID3D11Buffer *const *ppConstantBuffers
As the function receives a pointer to an array of my own wrapper, what would be the fastest way to create an array of ID3D11Buffers from it? To make it clearer:
void ...(DX11ConstantBuffer **pp, ....)
{
ID3D11Buffer** _pp = GetAllID3D11BufferElementsFrom(pp);
pDevcon->VSSetConstantBuffers(..., _pp, ...);
}
The function is meant to be called several times each frame.
The fastest way is proactively, i.e. to have maintained a contiguous array of ID3D11Buff* before needing to call VSSetConstantBuffers, for which you'd want a std::vector<ID3D11Buff*>. You could update the vector whenever DX11ConstantBuffer::pData is set, or DX11ConstantBuffer's destructor runs, and if you want better assurances around that you can make pData private and have accessor functions which can reliably intercept changes.
If you don't do it proactively, then with your current objects you've no choice but to iterate over the DX11ConstantBuffers and copy out the ID3D11Buf*s to an array/vector one-by-one....
You can make the wrapper inherites from the type it includes.

Assign value of variable in class C++

Hello I can't find out how to assign values to my variables that I am using in one of my class. I am getting error nonstatic member reference must be relative to a specific object so I am doing something wrong but I cant figure how o make it right.
class Triedenie_cisla{
public:
Triedenie_cisla(int *poleHodnot, int ddlzka);
int *pole, dlzka;
double bubble_time, selection_time, insert_time, quick_time;
vector<int> mnozina_int;
string vypis_pola();
void BubbleSort_int();
void SelectionSort_int();
void InsertSort_int();
void QuickSort_int();
};
Then in functions that make sorts, I measure the time and trying to assign the time to variables like that
Triedenie_cisla::insert_time = dif;
What I am doing wrong ? Thanks
You need to find a good book on C++, those are basic things.
nonstatic member reference must be relative to a specific object
means that to modify insert_time you must do it on existing object of class: Triedenie_cisla
Then in functions that make sorts, I measure the time and trying to assign the time to variables like that Triedenie_cisla::insert_time = dif;
you should do it like that:
void Triedenie_cisla::BubbleSort_int() {
// ....
insert_time = dif;
//
}
You have to create an object of your class. Then, assigning values is possible.
Triedenie_cisla obj;
obj.insert_time = dif;
Otherwise, the compiler assumes that you want to change the value of a static variable, ie.
a variable that exists once for the whole class. To do so, you would have to state
that insert_time is a static variable.
For example:
static double insert_time;
If I understand it well, you wish to set the value of insert_time inside your own sorting function which are already part of the class Triedenie_cisla.
Therefore you just need to do
this->insert_time = dif;
or even
insert_time = dif;
would be enough
You can not call a variable/method only using class name unless it is static variable/method of the class. Therefore, solution of your problem is:
Solution-1
First make a object of your class:
Triedenie_cisla object_1 = new Triedenie_cisla() ;
Call the variable using object name.
object_1.insert_time = dif;
Solution-2
You can solve this problem also using static key word in front of insert_time in the class declaration:
static double bubble_time, selection_time, insert_time, quick_time;