Why does my resized 2D vector reset my data - c++

I'm trying to save an Object in an 2D Vector. The vector needs to be sized at runtime. Therefore i use the resize function as mentioned in many other issues.
Her an broke down code example of my problem. So the code might not make sense but I get the same error.
Animation.h
class myPoint{
public:
int x, y;
myPoint(){}
myPoint(int x, int y) : x(x), y(y) {}
};
class AnimationFrame {
private:
std::vector<std::vector<myPoint>> sprites; //the important part
public:
void addSpritePoint(myPoint gridPos, myPoint tilePos);
...
};
class Animation {
private:
std::vector<AnimationFrame*> animationFrames;
public:
...
};
Animation.cpp
Animation::Animation() {}
int Animation::addAnimationFrame() {
AnimationFrame *newAnimationFrame = new AnimationFrame();
this->animationFrames.emplace_back(newAnimationFrame);
}
//AnimationFrame class
AnimationFrame::AnimationFrame(){
int w = 3; //just for the test
int h = 3;
this->sprites.resize(w, std::vector<myPoint>(h, myPoint(0,0)));
}
void AnimationFrame::addSpritePoint(myPoint gridPos, myPoint tilePos) {
this->sprites[gridPos.x][gridPos.y] = tilePos;
//printf(""); //breakpoint here
}
main.cpp
int main() {
Animation *a = new Animation();
a->addAnimationFrame();
a->getAnimationFrame(0).addSpritePoint(myPoint(0,0), myPoint(1,1));
a->getAnimationFrame(0).addSpritePoint(myPoint(0,1), myPoint(2,2));
a->getAnimationFrame(0).addSpritePoint(myPoint(0,2), myPoint(3,3));
}
I expect that the sprites 2D vector from my AnimationFrame class holds the values. When the first breakpoint kicks in the the Point(1,1) is in sprites(0,0) but when i now skip to the next breakpoint the values in sprites(0,0) is (0,0) again. So it resets the value. And i have no clue why.

The problem comes from the fact that Animation::getAnimationFrame() returns a copy of its internal data:
AnimationFrame Animation::getAnimationFrame(int frame) const;
So this modifies a temporary object and has no effect once the full expression has been evaluated:
a->getAnimationFrame(0).addSpritePoint(myPoint(0,0), myPoint(1,1));
The fix is simple: return by reference:
const AnimationFrame& Animation::getAnimationFrame(int frame) const
{
return *animationFrames[frame];
}
AnimationFrame& Animation::getAnimationFrame(int frame)
{
return *animationFrames[frame];
}
(yes, you need a const and a non-const version)

Related

Passing a variable from multiple classes to a function

I'm making a simple game of catching the fruit, but I've been having troubles with the collision logic and/or using the variables from the classes.
class row
{
public:
int x,y;
void setpoint (int xi, int yi)
{
x=xi;
y=yi;
}
float DownSpeed = 5;
void down () {
y = y+DownSpeed;
if (y==1000) {
y=0;
}
}
};
class fruit:public row
{
public:
void draw()
{
setcolor(11);
circle(x,y,20);
}
};
Then I have other classes to create the catcher, like so:
class catcher
{
protected:
float moveSpeed = 5;
public:
float catchX, catchY;
void setpoint (int xi, int yi)
{
catchX=xi;
catchY=yi;
}
void MoveLeft () {
catchX = catchX - moveSpeed;}
void MoveRight () {
catchX = catchX + moveSpeed;}
};
class character:public catcher
{
public:
void draw()
{
setcolor(15);
circle(catchX,catchY,50);
}
};
How do I call the variables of both circles into creating a collision function? I'm sorry if the codes are messy and ineffective, I'm just starting out and I'm stuck. Thanks!
Since both sets of variables are in the public part of the class, you should be able to create a function independent of either class and should be able to access the variables as long as they are declared.
void CheckCollision(float x, float y, float catchX, float catchY)
{
If(y =< catchY + 5)
{
//y resets
}
}
You’d want to check if it’s within a certain x range too though. I hope this solves your problem.
Since all the functions and variables are public. return the values of x, catchX from the functions modifying them. use the draw functions after you have the modified values.
for example modify your down function like this
int down()
{
y = y+DownSpeed;
if (y==1000)
{
y=0;
}
return y;
}
Modify the other function like wise and you will end up having your x,y and catchX, catchY values. create you collison function with these values.

Setting x or y of a POINT2f/VECTOR2f variable in a class using a member function

I have the following classes:
//----------------------------------------------------------------------
// CHARACTER CLASS
//----------------------------------------------------------------------
class Character
{
private:
POINT2f char_position;
public:
VECTOR2f char_velocity;
Character();
~Character();
// Mutators
void SetChar_Position(POINT2f p);
void SetChar_Velocity(VECTOR2f v);
// Accessors
POINT2f GetChar_Position();
VECTOR2f GetChar_Velocity();
};
//----------------------------------------------------------------------
// PLAYER CLASS - INHERITED FROM "CHARACTER" CLASS
//----------------------------------------------------------------------
class Player : public Character
{
private:
public:
int health;
Player();
~Player();
void SetPlayer_Health(int h);
int GetPlayer_Health();
};
So essentially the player class inherits from the character class.
The Character class has member function which lets you set the characters position and velocity, which take in a POINT2f and VECTOR2f.
Within my main bit of code I create a player character Player Player1 and than set the balls velocity and position if a button is pressed:
if (ui.isActive('A')) // Check to see if "A" key is pressed
{
// Player Ball
Player1.SetChar_Velocity.x = -12.0;
Player1.SetChar_Position.x += (Player1.GetChar_Velocity.x*dt);
Player1.SetChar_Velocity.x += (acceleration*dt);
}
I'm currently getting errors that say left of .x must have class/struct/union, so I change Player1.SetChar_Velocity.x = -12.0; to Player1.SetChar_Velocity().x = -12.0; which than brings up the error expression must have class type and to few arguments in function call.
Does anyone know of a method that will allow my to only manipulate the x number of the char_velocity only. also I understand that my code to Set the .x velocity isn't correct because I'm not passing in a VECTOR2f value.
In order to achieve what you want to do, you will want the return type of you Get_ methods to be a reference (wiki). Your code will then look like
class Character
{
private:
POINT2f char_position;
public:
VECTOR2f char_velocity;
// Accessors
POINT2f& GetChar_Position() { return char_position; }
VECTOR2f& GetChar_Velocity() { return char_velocity; }
};
Also, it is often advised or required to be able to preserve const-correctness in your code, so you might want to add
const POINT2f& GetChar_Position() const { return char_position; }
const VECTOR2f& GetChar_Velocity() const { return char_velocity; }
This will allow you to do some calls like
POINT2f current_pos = a_char.GetChar_Position(); // const
a_char.GetChar_Velocity().x += 2; // non-const
Please note that it is often advised to pass the structures as const references instead of copies (although this might not hold true depending on your c++ version and your types, you can see this question for clarification), hence change your
void SetChar_Position(POINT2f pos) { char_position = pos; }
void SetChar_Velocity(VECTOR2f vel) { char_velocity = vel; }
to
void SetChar_Position(const POINT2f& pos) { char_position = pos; }
void SetChar_Velocity(const VECTOR2f& vel) { char_velocity = vel; }

Seg fault when accessing a struct

I put the whole code on github: https://github.com/marianatuma/CG
I have a struct called point, declared in line.h, and a class line that has two points, start and end. EDIT: I didn't add it before, but Line inherits from GraphObj. graphObj.h:
class GraphObj {
private:
type t;
std::string name;
public:
GraphObj(type t, std::string name);
type getType();
std::string getName();
};
line.h:
#ifndef LINE_H
#define LINE_H
struct point {
double x;
double y;
};
class Line {
private:
point start;
point end;
public:
Line(type t, std::string name) : GraphObj(t, name) {};
void setStart(double x, double y);
void setEnd(double x, double y);
point getStart();
point getEnd();
};
#endif
line.cpp:
#include "line.h"
void Line::setStart(double x, double y) {
this->start.x = x;
this->start.y = y;
}
void Line::setEnd(double x, double y) {
this->end.x = x;
this->end.y = y;
}
point Line::getStart() {
return start;
}
point Line::getEnd() {
return end;
}
I always get a segmentation fault when I try accessing any of these points. I tried making them public, didn't work. I also tried using getters and it also didn't work. Here's how I'm initializing them:
The line is in a list of lines, called a display file, which will be used with cairo to draw them.
displayFile.h:
#ifndef DISPLAYFILE_H
#define DISPLAYFILE_H
#include <list>
#include "graphObj.h"
class DisplayFile {
private:
std::list<GraphObj*>* objectList;
std::list<GraphObj*>::iterator it;
int size;
public:
DisplayFile();
void add(GraphObj* g);
GraphObj* getNextObject();
void resetIterator();
int getSize();
};
#endif
displayFile.cpp:
#include "displayFile.h"
DisplayFile::DisplayFile() {
this->objectList = new std::list<GraphObj*>();
this->it = objectList->begin();
this->size = 0;
}
void DisplayFile::add(GraphObj* g) {
std::list<GraphObj*>::iterator tempIt;
tempIt = objectList->begin();
this->objectList->insert(tempIt, g);
this->size++;
}
GraphObj* DisplayFile::getNextObject() {
return *++it;
}
void DisplayFile::resetIterator() {
it = objectList->begin();
}
int DisplayFile::getSize() {
return size;
}
DisplayFile returns a GraphObj instead of the objectList, so it has to iterate through objectList by itself, hence the resetIterator (so when the main code is done traversing the list it will reset the iterator to the start of the list, but I'm not calling this method anywhere so far). The code in main.cpp where an instance of Line is used is below:
static void do_drawing(cairo_t *cr)
{
/* not using these right now
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_set_line_width(cr, 0.5);
*/
int size = df->getSize(); //df is the list
for(int i = 0; i < size; i++) {
Line* g = df->getNextObject();
point start = g->getStart();
}
}
The problem only starts when I try accessing the points, I can access other attributes from that line instance without problems. What am I doing wrong?
edit: I hope I've provided enough information, the main code is long and doesn't really have much to do with the line class, so I don't think it's relevant.
The problem lies with your list class.
class DisplayFile {
private:
std::list<GraphObj*>* objectList; // Why not just a list<GraphObj*>
std::list<GraphObj*>::iterator it; // Why use this?
int size; // WHY manually keep track of a STL container size?
public:
DisplayFile();
void add(GraphObj* g);
void resetIterator();
int getSize();
};
In your implementation file:
GraphObj* DisplayFile::getNextObject() {
return *++it;
}
As I already commented: this is the winner... Think about it, what if it already happens to be the last element on the list, and you ask for getNextObject()? Boom
I don't see why you couldn't just replace the entire DisplayFile class with a nice and plain std::list:
std::list<GraphObj*> objectList;
// I would also advice to change to smart pointers here
// for example: std::list<std::shared_ptr<GraphObj> > objectList;
// or std::list<std::unique_ptr<GraphObj> > objectList;
Then you would just use the STL methods to work with the list:
Add an item to the front: (for the sake of simplicity lets imagine that GraphObj has a default constructor)
GraphObj* g = new GraphObj();
objectList.push_front(g);
// If you change to smart pointers:
// objectList.push_front(std::make_shared<GraphObj>());
// or
// objectList.push_front(std::make_unique<GraphObj>());
Get the list size:
objectList.size();
Traverse the list:
for (std::list<GraphObj*>::const_iterator it = objectList.begin();
it != objectList.end();
++it)
{
point start = (*it)->getStart();
// or whatever you need to do here
}
Or with the much nicer range for:
for (const auto & graphObj : objectList)
{
point start = graphObj->getStart();
// or whatever you need to do here
}
Because you are not initilaizing the structs .
Change your constructor a bit
From this
Line(type t, std::string name) : GraphObj(t, name) {};
to
Line(type t, std::string name) : GraphObj(t, name) , start(),end() {};
This may help.
The problem might be coming from your getStart and getEnd because they return a point, which will create a copy(I think) of your start or end point, ie not using the point from line but copies. This usually isn't a big deal but if you want to change an x or y value and have the new value stick you'll need a reference to the original points x and y values.
Try this, change
point getStart();
point getEnd();
into
point *getStart() { return &start; }
point *getEnd() { return &end; }
and in your do_drawing(cairo_t *cr) change
point start = g->getStart();
to
point *start = g->getStart();
start->x = value; // or
double value = start->x; // or however you want to use start

Virtual function issue in C++ [duplicate]

This question already has answers here:
Why is virtual function not being called?
(6 answers)
Closed 9 years ago.
AoA,
I am making a console game of chess, But I am stuck at polymorphism, below is the classes and functions definitions
/* old Part
//Base Class
class Piece /*Parent class */
{
protected:
Position* pCoord;
std::string color;
char symbol;
public:
Piece(Position* Coord,std::string Color,char symbol);
Position GetCurrentPos();
std::string GetColor();
void SetColor(std::string color);
void Draw();
virtual bool SetPos(Position* newPos){MessageBox(NULL,L"Virtual Running",L"Error",MB_OK); return true;};
virtual ~Piece();
};
/* Inherited classes */
//Child classes
class Pawn: public Piece
{
private:
std::vector<Position>* allowPos;
public:
Pawn(Position* Coord,std::string Color,char symbol);
~Pawn();
std::vector<Position>* GetThreatendFields();
bool isValidMove(Position* newPos);
bool SetPos(Position* newPos);
};
//Child classes
class Bishops: public Piece
{
private:
std::vector<Position>* allowPos;
public:
Bishops(Position* Coord,std::string Color,char symbol);
~Bishops();
std::vector<Position>* GetThreatendFields();
bool isValidMove(Position* newPos);
bool SetPos(Position* newPos);
};
//Here is the implementation of child class function SetPos
bool Pawn::SetPos(Position* newPos)
{
bool isSet = false;
this->pCoord = new Position();
this->pCoord = newPos;
isSet = true;
MessageBox(NULL,L"Child function running",L"Yuhuu!",MB_OK);
return isSet;
}
class ChessBoard
{
private:
Position ptr; //dummy
int SelectedPiece;
vector<Piece> pPieceSet;
bool isSelected;
public:
ChessBoard();
~ChessBoard();
void ShowPieces(Player *p1,Player *p2);
void Draw();
void MouseActivity();
void Place(Piece& p);
};
//it just shows the peices acquired from player objects..dummy vector pointer
void ChessBoard::ShowPieces(Player* p1,Player* p2)
{
std::vector<Piece>* vPiece = p1->GetPieces();
for( int i=0;i<vPiece->size();i++ )
{
Piece& piece = vPiece->at(i);
Place(piece);
piece.Draw();
}
vPiece = p2->GetPieces();
for( int i=0;i<vPiece->size();i++ )
{
Piece& piece = vPiece->at(i);
Place(piece);
piece.Draw();
}
}
*/
/*new part
I did what you say
Player::std::vector<Piece*> *vPieceSet;
Player::Player(int turn)
{
this->turn = turn%2;
this->vPieceSet = new std::vector<Piece*>;
}
void Player::Initialize() //Initial and final ranges for position
{
//Initialization of pieces to their respective position
Position pos;
Piece *pPiece;
if( this->turn == 0 )
{
this->SetName("Player 1");
for( int i=8;i<16;i++ )
{
pos.SetPosition(i);
Pawn pPawn(&pos,"blue",'P');
pPiece = &pPawn;
this->vPieceSet->push_back(pPiece);
}
//other classes same as above
}
It runs fine at initialzation function(stores all classes fine) but when use function to get the vector object
std::vector<Piece*>* Player::GetPieces()
{
std::vector<Piece*>* tPieces = this->vPieceSet;
return tPieces;
}
//In main.cpp
it doesnot return the vector object
Player p1(0),p2(1);
p1.Initialize();
p2.Initialize(); //initialization done perfectly while debugging
vector<Piece*> *obj = p1.GetPieces(); //returns garbage
Piece* pObj = obj->at(0); //garbage
cout<<pObj->GetColor(); // garbage
*/new part
Sounds like I have another problem!
When you use polymorphism, what you are really trying to do is instantiate an object of derived type and call the methods on that object through a pointer or reference to the base object.
class Foo
{
public:
virtual void DoIt () { cout << "Foo"; }
};
class Bar
:
public Foo
{
public:
void DoIt () { cout << "Bar"; }
};
int main()
{
Foo* foo = new Bar;
foo->DoIt(); // OUTPUT = "Bar"
Foo& fooRef = *foo;
fooRef.DoIt(); // OUTPUT = "Bar"
}
In order for this to work, you need to use either a pointer or a reference to the object. You can't make a copy of the object using a the base class. If you make a copy, you will slice the object.
int main()
{
Foo* foo = new Bar;
foo->DoIt(); // OK, output = "Bar"
Foo fooCopy = *foo; // OOPS! sliced Bar
fooCopy.DoIt(); // WRONG -- output = "Foo"
}
In your code, the Piece class is intended to be polymorphic, and in your ChessBoard class you have a vector of this class:
class ChessBoard
{
private:
vector<Piece> pPieceSet;
};
Since this is a vector of the Piece object itself, and not a pointer-to-Piece, anything you put in here will be sliced. You need to change pPieceSet to be a vector of pointers-to-Piece:
vector <Piece*> pPieceSet;
You have further problems in Initialize, which need to be refactored anyway. For one thing, you have another vector of Piece objects, and there are two problems here. First, it needs to be a vector of pointers, and second, why do you need another vector at all when there is already one associated with the ChessBoard? I didn't thouroughly examine your code so maybe you do need it, but this seems like an error. There should probably just be one collection of pieces, in the ChessBoard.
In your Initialize method:
Piece *pPiece;
// ...
Pawn pPawn(&pos,"blue",'P');
pPiece = &pPawn;
vPieceSet.push_back(*pPiece);
There are a couple of problems. One, you are pushing back a sliced copy of the Piece, which will be fixed when you change your vector to store pointers. Second, if you just change this like so:
Piece *pPiece;
// ...
Pawn pPawn(&pos,"blue",'P');
pPiece = &pPawn;
vPieceSet.push_back(pPiece); // <-- not dereferencing
You will have a new problem because you'll be storing the pointer to a local (automatic) variable. Best is to do this:
Piece* pPiece = new Pawn (...);
// ...
vPieceSet.push_back (pPiece);
Please don't forget to delete everything you new. This is best handled by using smart pointers rather than raw pointers. In C++03 we have auto_ptr, but those can't go in a vector. Instead you'll need to use Boost or something else, or just store raw pointers. In C++11, we now have unique_ptr (preferred) and shared_ptr, which can go in to a vector.
In C++11, the best solution here is to have a vector declared as:
vector <unique_ptr <Piece> > pPieceSet;
...unless you have some compelling need to use shared_ptr instead.
As others have mentioned, it is a slicing issue, and the issue is created here:
class Player
{
private:
std::string pName;
std::vector<Piece> vPieceSet; // <-- This is your problem
int turn;
public:
Player(int turn);
~Player();
void Initialize();
std::string GetName();
void SetName(std::string Name);
int GetTurn();
std::vector<Piece>* GetPieces();
};
You are storing them in the vector as instances of Piece, which is slicing off the details of the piece (e.g. the Bishop implementation). You should modify it to something like:
class Player
{
private:
std::string pName;
std::vector<Piece*> vPieceSet; // or better, use a smart pointer wrapper
int turn;
public:
Player(int turn);
~Player();
void Initialize();
std::string GetName();
void SetName(std::string Name);
int GetTurn();
std::vector<Piece*> GetPieces(); // note this change as well
};
With your additional question/edit, you are getting another unrelated problem:
void Player::Initialize() //Initial and final ranges for position
{
Position pos; // position is declared inside the scope of Initialize
Piece *pPiece;
if( this->turn == 0 )
{
this->SetName("Player 1");
for( int i=8;i<16;i++ )
{
pos.SetPosition(i);
Pawn pPawn(&pos,"blue",'P'); // you are passing the address of position to the Pawn, and Pawn is within the scope of this loop
pPiece = &pPawn; // you are storing the address of the Pawn
this->vPieceSet->push_back(pPiece);
}
// Pawn is now out of scope and pPiece points to the memory location Pawn *used* to be at (but will likely be overwritten soon).
// As soon as this function returns, you have the same problem with pos
}
You need to allocate those variables on the heap (hence the reason we suggested smart pointer wrappers).

Accessing variables/functions from another class

I'm making a card game and I have a few classes.
I have a Hand class, a Player Class, a "Column" class (where the cards are placed on the screen after the hand) and I need each class to have access to the other classes' variables.
class Hand
{
private:
int **Hx,Hy;** //Hand X, Hand Y
int HAmount;//Amount of cards in Hand
int HOwner; //Player 1/2
int Limit; //Limit of cards in Hand
int HContents[8]; //Card Position in 54 card deck NOT card value.
bool Removed;
public:
Hand();
void Lim();
void Get_Card();
void Show();
void Set_Values(int y, int Own);
};
Then in another class I need to have access to some of the variables above.
void Card::show()
{
if((apply == true)
{
if((Track == true)&&(SelNum == TNum)&&(TOwner == COwner))
{
ScnPos = TAmount;
x = Tx;
y = Ty + ScnPos*10;
}
if((Hand == true)&&(**HOwner** == COwner))
{
x = **Hx** + ScnPos*45;
y = **Hy;**
}
apply_surface(x,y,Cards,Screen,&Clip[Pos]);
}
}
I've tried using class friendship and other methods but I can't make it work.
(obviously I have more variables which need this same treatment)
(ignore any errors in my code)
The errors in your code are the real problem here. there is no reason that a Card will access a Hand's private member. this is design error, and your other problems are just trying to tell you that.
Well, you should make getters and setters for your variables. E.g.:
class Test {
private: int a;
public: int GetA() {
return this->a;
}
void SetA(int a) {
this->a = a;
}
}