I am just getting back into programming, so forgive me if this is very silly.
I have 2 classes (for now). One is the Windows Form class, where I am using a Button_Click event to trigger a communication port opening. I want to pass data that the user entered on the form on to the Communication class for further processing (sending).
This is the part that initializes and calls the Communication class:
wchar_t * data = new wchar_t[nLength];
*data = *wch;
SerialCommunication comm1;
bool comm1ok = comm1.SerialWrite(data);
Variable "data" is a pointer, so I want to pass its address to the other class to use.
This is my 2nd class:
bool SerialCommunication::SerialWrite(wchar_t * datar){...
But the data never makes it there. It goes out of scope as soon as the SerialWrite() function starts up. Do I need to declare this pointer in some other way to make sure it doesn't disappear when I move between classes?
The classes are both public, as far as I know (well, I wrote the SerialCommunication one, so I know it's public).
What am I doing wrong? What should I change?
Thanks!
This:
*data = *wch;
does not do what you think (or what I assume you think). It just copies the first element of wch into the first element of data.
Related
I guess this is kinda far-fetched, but basically, I'm trying to create an instance of a class that I need to work on as if it were globally declared but initialize it once I have obtained some data from memory (previously stored data in the microcontroller). It's a project with an ESP8266 MCU that allows you to configure an led display via wifi, and for that my teammates wanted to make use of an already existing library, the problem is that in order for the user to be able to change the number of devices that they're going to use I would need to (from what I can gather, I started learning about classes a few days ago, I'm still in diapers) use the constructor again since that's when you're supposed to provide the number of devices (after that I'm not sure where I could change that variable again, I don't even know exactly what the constructor does because it's only declared in the .h file but then I wasn't able to find where is it that they define the function. There is a variable in the class that seems to have something to do with that but it's private).
Originally I thought of simply passing the value to the void loop() and the other functions I use in the code, but that proved to be ineffective given that I also use another library called ESPAsyncwebserver that returns (I think that's how it works) to the void setup() (to all the places where I used 'objectoftheclass.on()' because it makes a callback) function whenever there's an HTTP request so it throws an error saying that the object was not declared in that scope (which is where I'd be creating it in). The other solution I thought of was to copy one object into an already existing global one once I had the data I needed from memory but that also throws an error.
Is there a way to allocate the memory required for a class outside of main (like a global variable) and then make an instance of that class later on but in that space? Or like, maybe a way of not using a constructor for that object until a later point in time (without really using the object at all before I use the constructor)?
I didn't wanna post the code here because it is both messy and unnecessarily lengthy for a post but tell me if it would help because I'm not quite sure if the idea of what I need here is all that clear, thanks.
I am in a bit of a pickle. I am using the boost::serialization in order to save/load a pointer from memory. The saving part, I have no issues. I was able to verify that the serialization class is able to save the pointer without any issue. As a side note, the pointer class is a custom class that I created.
Some background. I am using the wxwidgets library to create a GUI. I am using the latest version (v3.1.0). The object inherits from the wxGLCanvas class. Which requires a pointer to the parent window. The class is being used to draw a grid on the screen and the user can interact with the grid by placing geometry shapes (mainly squares, arcs, and lines). Each shape is its own class. Within my class, I have datatypes that specify the grid step size, the placement of the camera, the zoom level, and the geometry shape vectors. All of these are able to be saved. Note that my class does specify other data types as well but I am not saving these so they are irrelevant to the discussion. As a side note, the class in question is called modelDefinition
Now, we come to the load part of the class. My current implementation is as such:
void MainFrame::load(string filePath)
{
std::ifstream loadFile(filePath);
if(loadFile.is_open())
{
modelDefinition temp(this, wxPoint(6, 6), this->GetClientSize(), _problemDefinition, this->GetStatusBar());
//modelDefinition tempDefintion = (*_model);
boost::archive::text_iarchive ia(loadFile);
ia >> _problemDefinition;
ia >> temp;
temp.copyModel(*_model);
//*_model = temp;
//(*_model) = tempDefintion;
_model->Refresh();
}
}
Implementation of the copy function:
void copyModel(modelDefinition &target)
{
target.setGridPreferences(_preferences);
target.setEditor(_editor);
target.setZoomX(_zoomX);
target.setZoomY(_zoomY);
target.setCameraX(_cameraX);
target.setCameraY(_cameraY);
}
My idea is this, that I create a temporary variable and initialize it to the values that I need it to be. Currently, it is empty. Then, I will load the data into the temporary variable and then copy the needed data structures into my main variable. However, the program crashes at ia >> temp. I am not sure why right now. I go into the debugger and I do not get access to the call stack after the crash. I have a feeling that it is crashing within the boost library. I did place a break point within the serialize function in modelDefinition and the program never made it.
I did come across this forum posting:
Boost serialization with pointers and non-default constructor
To be honest, I am not too sure if it applies to me. I am trying to think of a way that does but so far I can not find any reason that applies to me.
Here is the declaraction of the modelDefinition constructor:
modelDefinition::modelDefinition(wxWindow *par, const wxPoint &point, const wxSize &size, problemDefinition &definition, wxStatusBarBase *statusBar) : wxGLCanvas(par, wxID_ANY, NULL, point, size, wxBORDER_DOUBLE | wxBORDER_RAISED)
par MUST have a value. Null values are not accepted. I did see that the forum post did override the load function and grabbed the values and passed them into the constructor of the class. However, in my case, par is a this pointer and I am not able to serialize the function and load this back into the program (besides, this will change on every single function call). this refers back to the parent window. And overriding the load function in a different namespace prevent me from passing this into the function. So basically, that option is out of the water (unless I am missing something).
Again, since I can't pass in NULL into the wxGLCanvas constructor, this option is off the table:
modelDefinition _model = new modelDefinition();
modelDefinition::modelDefinition() : wxGLCanvas(NULL, 0)
And I believe that this option is also off the table since my parent window that would be associated with the canvas is in a different namespace:
template<class Archive>
inline void load_construct_data(
Archive & ar, modelDefintion * foo, const unsigned int file_version
){
double test;// There would be more after this but to simplify the posting, I am just throwing this in here.
ar >> test;
::new(modelDefintion)_model(this, test); // Yeah, I don't think that this is going to work here.
}
Again, this would need to be pointing to the parent window, which I don't think that I have access to.
So right now, I am a little lost on my options. So far, I am thinking that I will continue to be working on the first case to see where the program is crashing.
Although, I could really use someone's help in solving this issue. How can I load back the data structure of a non-default constructor pointer where I cannot save the data from the inherited object (because modelDefinition inherits from wxGLCanvas data type and I am unable to save this data type)?
Yes, I am aware of the minimal example. It will take me sometime to create a minimal example. If the forum people need it to effectively come up with a solution, then I will do it and post here. But again, it will take time and could be rather long.
Yes, load/save construct data is the tool to deal with non-default constructibles.
Your problem is different: you need state from outside because you are trying to load objects that require the state during construction, but it never got saved in the first place. Had it been, you could re-create the parent window just like it existed during serialization.
The only "workaround" I can see here is to use global state (i.e. access it through (thread) global variables).
I do not recommend it, but you're in a pickle so it's good to think about workarounds, even bad ones
As soon as you salvaged your data from the old-style archives, I suggest serializing into a format that
saves all required construct data
serializes a data struct not tied to the GUI elements
Of course I don't know about the over-arching goal here, so I can't say which approach is more apt, but without context I'd always strife for separation of concerns, i.e. de-coupling the serialization from any UI elements.
i wrote a program for a pic32mx575f512h in C++. the processor has 6 uarts and the program routes the uart packets from one to another. the program is written using two generic classes. a receive class and a send class. when the objects for these classes are declared a struct with settings is handed to them to make them unique.
to ease interconnecting these objects the receive class is handed an array of send class pointers. when a message arrives say for uart "one" on any of the other uarts the receive class calls the appropriate send class from the array by using the address as the array index. for example:
send_pointer[received_address]->data_put()...
the code is tested and works well.
now i need to expand the code further to add debugging through usb. the usb stack is taken care of i just need a way to pass data from the receive class to the send class including a function for the usb. where i'm struggling is that the usb send handler is completely different from the the uart send class. i would like to add another member to the array of send pointers but that's not possible. i've tried making an array of function pointers but C++ won't allow storing the member of a class in a function pointer.
is there another way i can do this so i can still use the address as an index of where the message needs to go?
In order to execute methods of a class, you either need an instance, or the method has to be declared as static.
Search the internet for "c++ FAQ pointer to member function".
You may need to redesign you program or use a Factory Design pattern.
I am currently working on a game where I have a couple of classes which each handles their own gameobjects. For these classes to actually represent something in the game they need to use another class which is the animation_manager.
The animation_manager handles the loading, drawing and moving of objects on the screen and is created at startup.
What would be the smartest way of passing the manager to the classes which handles the gameobjects?
Should it be done by a public pointer, by assigning it to a static pointer in the object class which every gameobject inherits from or should I simply just pass it as a pointer to the gameobjects/objects class constructor?
I am using C++03 so no new fancy fixes :P
EDIT 1:
There has been a lot of good suggestions and I am thankful for that.
Now I will not use weak pointers since I dont need the object handlers to take care of the deletion of the pointer as its going to exist from the beginning to the end of the program.
Singletons wont fit my needs either as I dont want any class to have access to it.
One thing that came to mind when reading the replies is: Would it be a good idea to make a static reference for the anim_handler in the Object class which all the handling classes inherits from?
I'd prefer the passing by constructor.
This way you can establish an invariant (i.e. the manager is always present) whereas later setting a field does not ensure it's always done.
Like thomas just posted you should use a shared_ptr or something similar (if not using C++11).
I try not to use static fields (except for constants) since it prevents you to use different manager objects for each gameobject. (Think of a debugging/logging manager class, or another wrapped manager).
You can keep this shared manager object in a shared pointer which is added to C++11 (or you can use Boost library) standard as shared_ptr.
It has a reference counting mechanism such that you do not have to worry about the ownership and memory management of related object.
Every gameobject can keep a shared pointer member to your animation_manager.
If your animator_manager is a unique object, another approach could be defining it as a signleton, eventually removing the need for storing any reference to it in the gameobjects handling classes and using some sort of static method like animation_manager::getInstance() to use it.
The performance impact could be easily minimized by reducing the calls to the getInstance() method, but it really depends on your design, can't be sure it would fit.
you should give it as a reference (if possible a reference to a const), not a pointer. Only if you would have a class hierarchy of animation managers a pointer (if possible const to a const) would make sense. In the latter case, you should consider using boost's shared_ptr. If move to C++11 later, the changes to C++11's shared_ptr are minimal.
From the design point of view, you might also think about using an observer pattern, so the animation manager can decide on its own when it is the right time to render without having too much boilerplate code.
Passing a reference would be the most favorable way when thinking as a good software architect, because it will allow easier testing and mocking.
However, a game(engine) is - in my opinion - such a special case of software where "good patterns" can be counterproductive sometimes. You will nearly always end up in the situation that you need some manager classes everywhere.
You might want to look at the god-object anti-pattern, to make all common managers available globally. I use one(!) globally accessible instance of an "Application"-instance, which contains some bootstrapping code and references to the most common manager classes, like this:
// application.h
class CApplication {
void init(int argc, char **argv); // init managers & co here
void shutdown();
void run();
CMemoryManager * memory;
CSystemManager * system;
CAudioManager * sound;
CInputManager * input;
};
// globals.h
CApplication * app;
// main.c
#include "globals.h"
int main(int argc, char ** argv) {
app = new CApplication();
app->init(argc, argv);
app->run();
app->shutdown();
return 0;
}
// some_other_file.cpp
#include "globals.h"
void doSomething() {
// ...
app->input->keyDown(...);
// ...
}
Bad style? Probably. Does it work? For me it does. Feedback is also welcome as comment!
I'm adding another answer because it's quite a different approach, when compared with the previuos one.
First of all I should clarify that I'm not experienced in game programming! :)
Anyway, as I was suggesting in my previous comments, maybe, I would take a different route. Immagine that you have a "game field" with walls and other static elemnts, and a number of "actors", like monsters, the player alter ego and so on...
I would probably write an ancestor "Actor", subcalssing "Player" and "Enemy" classes, then subclassing "Enemy" into "Dragon", "Zombie", "Crocodile" and so on. Maybe Actor could have a bounch of common attributes, like "location", "speed", "strenght", "energy", "direction", "destination" and a status, say "moving", "sleeping", "eating the player", "being eated"...
A typical game iteration, could be something like:
1) get input from the player
2) call a method of the player actor object, something like:
player->move(east, fast);
3) cycle trough a list of actors to update their status, say:
for (int i(0); i < enemies.size(); i++) {
// Checks the player position in the gamefield and setup a strategy to eat him
enemies[i]->updateStatus(player, gamingField);
}
4) cycle trough the list of actors and move them:
animator->animate(player);
for (int i(0); i < enemies.size(); i++) {
animator->animate(enemies[i]);
}
5) check if something interesting has happened (the player has been eaten by the crocodile)
I mean: this is a totally different approach, but I think that isolating the actors logic could be a good idea, and you could avoid the original problem completely.
It seems to me that there are no explicit answer for this question, but rather multiple ways of doing it which each has their own opinion on.
In case anyone else have the same question I am going to list them below:
Shared_Pointer:
This method will keep track of the amount of used pointers pointing to the address and if that count hits zero, then it will deallocate the memory. Is available in C++11 and the boost library.
A shared pointer can be passed to other objects the same way as a normal pointer.
Suggested by ogni42
Passed by constructor:
A pointer or reference can be passed to the object when it is being constructed. The upside of using a reference is that the programmer can't accidentally use delete on the pointer.
Prefered by Onur.
Use of singletons
Singletons are an unique extern class which holds a pointer to the object which can be accessed through a function.
This was suggested by Albert
Global variables
Simply a globally declared variables. Personally I do not recommend these as they can become a mess as they become available even from code which you wont need them in.
Suggested by Sir PanCake
static variables
This is what I ended up using. I made it so that only objects which inherited from my Object class could access the anim_handler. The way I did this was by declaring Object a friend of my anim_handler and then I made the static variable to retrieve the handler protected
Anyways, thanks for the support everyone! I appreciates it a lot and I even learned something new! :)
Background of the issue
I'm working on a basic battleship-like spinoff game that I want to continue to add features to over time in C++ (no graphics). Currently I have a 50 x 75 game board, represented with a 2D vector (called GameBoard) that is currently of type char. I create a game board and set each location with '.' char. As you guess coordinates, previously guessed locations are marked with '-' and hits are marked with 'X'
Where I'm at with the program
I decided to modify the game to enable some more features. I'm not too far along, but sketching up a design in pseudocode started making me think more about how I can go about this upgrade.
Instead of the GameBoard being chars, I'm creating a class called Block (an empty space on the board), which will now have a x and y coordinate variables, along with a char variable to visually display the correct char. Block has the ability to hold the object "Feature" which breaks off into derived classes of "feature." You can scroll to the very bottom for more detail about these classes.
This is how my class hierarchy tree goes:
feature
item vehicle
gold nuke plane
What I need help with
I basically have the outline/structure setup for what I want to do. Now I just need some help kickstarting it to get everything to connect. I'm pretty bad with determining when and how to use pointers.
A.) Should I change GameBoard to hold pointers of the Block class? Or actual Block objects?
- And would Block hold a pointer to a Feature or the actual Feature object?
B.) How do I add a Feature variable that can be empty or given a value? Do I just set it to NULL?
C.) Do I need a custom copy constructor to swap the Feature value of Block?
D.) How do I go about removing the Feature object from Block if the player uses it?
E.) Can there be more than 1 Feature on a single Block occasionally?
F.) How do I declare the Block and Feature classes such that Block can hold a Feature and Feature is already derived from another class (not included in this post).
Extra Details about my classes
So GameBoard is the vector that will store Blocks. Blocks are essentially the individual spaces on the board. Block contains coordinates for its location, a char to represent it, and the possibility to hold a Feature object, but most of the time the Block won't be holding a feature. Feature is derived from Block and acts as a bonus reward in the game. So Feature branches into 2 more derived classes, an Item Feature or Vehicle. And so on.
When the player chooses coordinates, a method will go to that Block on/in the GameBoard and first check if the char value represents a valid space that hasn't been used before. Then it checks the contents of this Block for Feature. Feature may be empty or contain a derived Feature object.
Ok that concludes my novel. Sorry for writing so much. I figure the best way to get help is to let the helpers know what's going on. PLEASE don't respond telling me to "get to the point." I know I know.. Let me know if I'm missing details. Thanks!
I am assuming you want to keep your class structure. At your point of abstraction I am suggesting using shared and uniqe pointer via (C++11 or Boost). If you're pretty bad at pointers learn how uniqe and shared pointer work and try to stick with those. Remember to keep the object's life scope as short as possible.
A.) Should I change GameBoard to hold pointers of the Block class? Or actual Block objects? And would Block hold a pointer to a Feature or the actual Feature object?
I want keep this GameBoard elements as immutable uniqe pointers or keep actual instances.
B.) How do I add a Feature variable that can be empty or given a value? Do I just set it to NULL?
You have decided to keep Feature inside Block - ok. If so keep it as shared pointer. If there is no feature shared pointer will be empty.
C.) Do I need a custom copy constructor to swap the Feature value of Block?
Only if there is something dynamic/unusual inside Feature. What will the Feature hold?
D.) How do I go about removing the Feature object from Block if the player uses it?
If you use shared pointer there's no problem. Even if the Feature have changed during handling previous Feature, Feature will be handle correctly and destroyed when it's no longer required by GameBoard.
E.) Can there be more than 1 Feature on a single Block occasionally?
You have to ask yourself this question - does your game require handling this situation? If so simply hold vector/map/set/array (depending on your requirements) of shared pointers to Features.
F.) How do I declare the Block and Feature classes such that Block can hold a Feature and Feature is already derived from another class (not included in this post).
I am not sure if I understand the question correctly:
class Feature : public GameElement {
/* Feature implementation */
}
class Block {
shared_ptr<Feature> mFeature;
/* Block implementation */
};
Does it answer your question ?
I am not sure if it is a good idea to derive class feature from class block
I would rather use a pointer to feature within each instance of block, this way the pointer is NULL if there is no feature. This pointer would be pointer to the base class feature in your case. I encourage use of virtual methods to access individual features.
when a feature is used up, delete it and set pointer to it to NULL. (the pointer that is within the block instance)
if you want to have more than one feature per block at a time, consider using some kind of array/stack of pointers.
in my opinion the GameBoard should hold actual instances (not pointers) of Blocks.
I do not understand what do you mean by:
Do I need a custom copy constructor to swap the Feature value of Block?
I hope this helps =).
I think it would be a good idea of your GameBoard is a container for GameObject pointers. You don't need to create a whole new class and call it Block - all this is implied. There is also no need to track the coordinates of blocks, since they are arranged in order. A GameObject would be the base class for the hierarchy of game elements - in your case that would be a Feature, the reason I used GameObject is because Feature is just not very descriptive - the term is too broad with wide scope.
When the game is started, your GameBoard can be populated by null pointers which are subsequently substituted by the actual game elements that are created and added to the board.
You only need to implement copy constructor and assignment operator if you have dynamically allocated data. If not, the compiler will generate a perfectly good version that will do raw object copy.
That being said, you'd better not move actual object instances around, and with the proposed method of using pointers instead, you will only be moving pointers, which is much simpler and faster.
If you want to remove a Feature, just delete the actual object and set its pointer in the board to null.
If you implement a parent/child relation you can have a tree of GameObjects in each block, and you can traverse that tree recursively and do to the tree elements as you will.
A well designed polymorphic hierarchy will allow you to put pretty much anything as long as it is derived from your base class.