C++ Std::vector confusion | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C++ Std::vector confusion

I try to .push_back() a new obj instance of a class into a vector, but it throws an error saying "attempting to reference a deleted function". Could anyone help me out?

26th Mar 2017, 3:51 PM
denzal maradona
denzal maradona - avatar
7 Answers
+ 2
@NicoLoos is right. The correct function is typing is ".push_back(object)" ************* MyClass object; std::vector<MyClass> myVector; myVector.push_back(object); ************* This is how it would be done, in a very basic way. Hope this helps and happy coding!
26th Mar 2017, 4:55 PM
Zeke Williams
Zeke Williams - avatar
+ 2
Ohhhhh I think what is happening is that you create a local variable of type Projectiles somewhere, and then the scope for that object doesn't include your else if statement; this is just the assumption I'm making based on the error you received. Does that make sense? For an example: void makeProjectile() { Projectiles projobj; } // scope of projobj ends here else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { projectilesvector.push_back(projobj); // doesn't recognize projobj because it has... } // ...destructed above. Let me know if that's what is happening in your code. Maybe more of your code could help, like a link to a playground, even if it won't run.
27th Mar 2017, 3:57 AM
Zeke Williams
Zeke Williams - avatar
0
i guess the correct writing is ".push_back()"...
26th Mar 2017, 4:22 PM
Nico Loos
Nico Loos - avatar
0
yeah I made the mistake when writing the question, I used the correct syntax in my app
26th Mar 2017, 5:22 PM
denzal maradona
denzal maradona - avatar
0
could you paste the code or at least a snippet Plesse?
26th Mar 2017, 5:36 PM
Nico Loos
Nico Loos - avatar
0
Projectiles projobj; std::vector<Projectiles> projectilesvector; *gap* else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { projectilesvector.push_back(projobj); }
26th Mar 2017, 6:28 PM
denzal maradona
denzal maradona - avatar
0
I managed to resolve it. I had to create an overloaded constructor as the default constructor would be destroyed once I was out of scope, and when actually creating the objects. I'll provide some of the code later on if anyone requires it
27th Mar 2017, 7:03 AM
denzal maradona
denzal maradona - avatar