I'd like to access to a double pointer which is located in another class "Board".
class Board
{
public:
Board(void);
Board(unsigned int xSize, unsigned int ySize);
~Board(void);
void SetObjectManager(ObjectManager* pObm);
void SetBlock(Block* block);
void LoadBoard(void);
void InitBoard(void);
//Other Functions...
private:
ObjectManager* m_obm;
Block* m_block;
//pointer to pointer to a int. (for 2 dimensional-array)
int **m_board;
};
First, the Board class. at the last line of class, you can see m_board.
I want to change this value in outside of this class.
Like this,
void Block::InitBlock(void)
{
int randPiece = Random::GIRand().RandInt(0, 1);
int randPos = Random::GIRand().RandInt(0, 10);
switch (randPiece)
{
case 0:
m_piece[2][1] = 1;
m_piece[2][2] = 1;
m_piece[2][3] = 1;
m_piece[3][3] = 1;
break;
//Other cases are here...
}
std::cout << "RandPos : " << randPos << std::endl;
std::cout << "RandPiece : " << randPiece << std::endl;
for (int y = 0; y < m_ySize; ++y)
{
for (int x = 0, pX = randPos; x < m_xSize; ++x, ++randPos)
{
if (m_piece[x][y] != 0)
m_board->SetBoardStatus(randPos, y, 1);
}
}
}
But, When I run this program, It blows up at SetBoardStatus(int, int, int)
SetBoardStatus looks like this,
void Board::SetBoardStatus(int x, int y, int value)
{
m_board[x][y] = value; //Visual Studio breaks the program here.
}
I allocate the double pointer properly.
And I set the board at the outside of this classes.
void Block::SetBoard(Board* board)
{
m_board = board;
}
And this is my block class.
class Block
{
public:
Block(void);
~Block(void);
void SetObjectManager(ObjectManager* pObm);
void LoadBlock (void);
void InitBlock (void);
void UpdateBlock (void);
void ReleaseBlock (void);
void SetBoard(Board* board);
private:
ObjectManager* m_obm;
Board* m_board;
int **m_piece;
int m_xSize;
int m_ySize;
};
Consider inheriting Block in Board; This will eliminate any possible de-referencing errors or bugs, as you can access the pointer right away.
Related
So in my program, I'm using polymorphism, which could also explain some of the issues that I'm having.
This is my pure abstract class:
class Event {
public:
Event();
~Event();
virtual int returnType();
};
Then I have a room class that sets events to a particular room:
class Room {
private:
Event * e;
bool player = false;
bool bEvent = false;
public:
Room();
~Room();
Event * getEvent();
void setEvent(Event *);
bool getPlayer();
void setPlayer(bool);
bool getBoolEvent();
void setBoolEvent(bool);
};
And here are my function definitions:
Event * Room::getEvent() {
return e;
}
void Room::setEvent(Event * n) {
e = n;
}
bool Room::getPlayer() {
return player;
}
void Room::setPlayer(bool p) {
player = p;
}
bool Room::getBoolEvent() {
return bEvent;
}
void Room::setBoolEvent(bool b) {
bEvent = b;
}
Here is my bats class which is a derived class from event: The functions are the same, so here are the function definitions:
int Bats::returnType() {
return 1;
}
So in my program, I am using a 2d vector of Rooms, and then assigning events to these rooms via polymorphism. The problem is that I don't think the changes are persisting, at least with the polymorphism, even when passing by reference.
Here is the function where I am setting the bat event to a certain room in the 2d vector:
vector<vector<Room>> Game::setEvents(vector<vector<Room>> &grid) {
Bats b1;
Event * eb1 = &b1;
//Set player
int r1 = rand()%gridSize;
int r2 = rand()%gridSize;
grid[r1][r2].setPlayer(true);
//Set bats
grid[0][0].setBoolEvent(true);
grid[0][0].setEvent(eb1);
cout << "Function example: " << grid[0][0].getEvent()->returnType() << endl;
return grid;
}
As an output I get Function example: 1;
However, when we move into the main (in this case Game::play()) function, these changes don't hold.
void Game::play() {
srand(time(NULL));
//Create vector
vector<vector<Room>> grid;
//Fill vector
fillGrid(grid);
//Set player and events
grid = setEvents(grid);
for (int i = 0; i < gridSize; i++) {
for (int j = 0; j < gridSize; j++) {
if (grid[i][j].getBoolEvent() == true) {
cout << i << " " << j << endl;
cout << grid[i][j].getEvent()->returnType() << endl;
}
}
}
}
As an output I get 0 0 and then a seg fault.
Although the boolEvent is still true, for some reason I get a segmentation fault when trying to call returnType(), even though it worked in the setEvents() function. What am I doing wrong with polymorphism?
Background
I am self-learning C++ from this course, and I am unsure whether I understand why exactly my syntax was wrong.
Problem
Please see the two versions of the PointArray constructor in geometry_test.cpp. The first one gives an error, while the second one comes from the solution manual. In my (probably flawed) understanding, the two versions should be equivalent. Where have I gone wrong? When am I referring to the member attributes points and size? and when am I referring to the input variables points and size?
Thank you for any clarifications or suggestions to references I should check out.
Related query
How might the error message suggest a solution?
Code
geometry_test.h
class Point {
private:
int x, y;
public:
Point(int create_x = 0, int create_y = 0) { x = create_x; y = create_y; };
int getX() const { return x; };
int getY() const { return y; };
void setX(const int new_x) { x = new_x; };
void setY(const int new_y) { y = new_y; };
};
class PointArray {
private:
Point *points;
int size;
void resize(int n);
public:
PointArray(const Point points[], const int size);
~PointArray() { delete[] points; };
};
geometry_test.cpp
#include "geometry.h"
#include <iostream>
using std::cout;
PointArray::PointArray(const Point points[], const int size) { // breaks
points = new Point[size];
this->size = size;
for (int i = 0; i < size; ++i) { this->points[i] = points[i]; }
}
/*
PointArray::PointArray(const Point ptsToCp[], const int toCpSz) { // works
points = new Point[toCpSz];
size = toCpSz;
for (int i = 0; i < toCpSz; ++i) { points[i] = ptsToCp[i]; }
}
*/
int main() {
Point p1(1, 0);
Point p2(2, 0);
Point p3(1, 1);
Point ptarray[3] = {p1, p2, p3};
PointArray pa(ptarray, 3);
cout << p1.getX() << ", " << p1.getY() << "\n";
cout << p2.getX() << ", " << p2.getY() << "\n";
cout << p3.getX() << ", " << p3.getY() << "\n";
return 0;
}
Error message
geometry_test(17467,0x11b51adc0) malloc: *** error for object 0x7ffee4705690: pointer being freed was not allocated
geometry_test(17467,0x11b51adc0) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6
I have a public class in which I create an array, this array takes its size from the constructor and needs to be used in other functions (including int main). Therefore the variable must be public. my code looks something along these lines:
class myclass {
public:
int parameter1;
int parameter2;
myclass(int p, int p2) {
parameter1 = p;
parameter2 = p2;
}
void makeArray() {
int array[parameter1][parameter2]; //I want this array to be public as the next method needs access to it
}
void otherFunction() {
array[1][2] = 5; //just an example of what i need to do
}
}
Look up how to use pointers and dynamic memory..
To do what you want would be something like:
class myclass {
public:
int parameter1;
int parameter2;
int **a;
myclass(int p, int p2) {
parameter1 = p;
parameter2 = p2;
a = nullptr;
}
~myclass() {
// TODO: delete "a"
}
void makeArray() {
// TODO: delete "a" if it has already been allocated
a = new *int[parameter1];
for (int i = 0; i < parameter1; ++i) {
a[i] = new int[parameter2];
}
}
void otherFunction() {
// TODO: check that "a" has already been allocated
a[1][2] = 5; //just an example of what i need to do
}
}
You could also allocate the array in the constructor since you have the necessary information being passed in already.
This is more optimized way to do the same thing:
class myclass {
public:
int parameter1;
int parameter2;
int *array;
myclass(int p1, int p2) {
parameter1 = p1;
parameter2 = p2;
}
void makeArray() {
array = new int[parameter1*parameter2];
}
void otherFunction() {
// ary[i][j] is then rewritten as ary[i*sizeY+j]
array[1*parameter2+2] = 5;
}
};
int main()
{
int sizeX = 5;
int sizeY = 5;
myclass m1(sizeX,sizeY);
m1.makeArray();
m1.otherFunction();
cout << m1.array[1*sizeY+2] << endl;
return 0;
}
I'm building a domino game and trying to make a function that adds a Stone to a pile.
This is the Stone class:
class Stone
{
public:
Stone(){ left = 0; right = 0; };
Stone(int x, int y){ left = x; right = y; };
void turnStone();
bool comStones(const Stone&);
void printOpen();
void printClosed();
friend class Pile;
friend class Game;
private:
int left, right;
};
And this is the Pile class:
class Pile
{
public:
Pile(){};
Stone indexfun(int);
void printOpen();
void printClosed();
void fillPile();
void randPile();
void addStone(Stone&);
void remStone(Stone&);
friend class Player;
friend class Game;
private:
Stone* list;
int size=0;
};
Now the function I built for adding a stone to the pile is:
void Pile::addStone(Stone& newStone) {
Stone* newList = new Stone[size + 1];
int i;
for (i = 0; i < size; i++)
{
newList[i] = list[i];
}
newList[i] = newStone;
delete[] list;
list = newList;
size++;
}
When I try and build the newlist array it throws me out of the program. can't find the reason. Help anyone?
the previous functions and more classes in the project:
class Game
{
public:
Game(char*);
void run();
private:
Player human, computer;
Pile box, table;
int start, finish;
void playerMove(int);
void checkPile(int);
bool checkMove(int,int);
bool whosFirst();
bool checkGame();
void printTable();
};
class Player
{
public:
Player(){};
void addStone(Stone&);
void remStone(Stone&);
void printPile();
Stone* searchStone();
friend class Game;
private:
char* name;
Pile pie;
};
void Game::run() {
cout << "starting the game" << endl;
box.fillPile();
box.size = 28;
box.randPile();
for (int i = 0; i < 7; i++)
{
human.addStone(box.list[i]);
box.remStone(box.list[i]);
computer.addStone(box.list[i]);
box.remStone(box.list[i]);
}
}
void Player::addStone(Stone& added) {
pie.addStone(added);
}
int main()
{
char name[80];
cout << "enter your name" << endl;
cin >> name;
Game game(name);
game.run();
}
Maybe change the "list" variable name to "list1" or something like that. "list" is a STL container, just like vector.
I am trying to create a vector of objects but i have some issues. I can't push_back over 19 objects to my vector because it shows up an error message of bad_alloc.
I try to resize my vector with resize() or reserve() but still nothing.
For resize(), I read that you need to provide 2 arguments to resize a vector.But still nothing.
When I try to use it without push_back it shows error: expected primary-expression before ')' token.
#define N 10 //ari8mos seirwn tou xarth
#define M 10 //ari8mos sthlwn tou xarth
#define TREAS 100//posothta 8usaurou
#define PORTS 100//ari8mos limaniwn
extern void ships(map (&myArray)[N][M], vector<ship> &myShips);
void ships(map (&myArray)[N][M], vector<ship> &myShips)
{
int i,j,y;
srand ( time(NULL) );
//myShips.reserve(21);
//myShips.resize(20,ship);
cout << myShips.capacity() << endl;
int x=0;
for( i = 0; i <19 ; i++){
myShips.push_back(pirate(rand() % N,rand() % M,100,100,100,1,'#',myArray,myShips));
}
for( i=0;i<myShips.size();i++ ){
cout << myShips[i].get_symbol() << " ";
}
}
here is the rest of code to help you understand:
class ship
{
protected:
int i,j,x2,y2;
//vector<vector<map> > myArray;
//ship (&myShips)[N][M];
int x;
int y;
map (myArray)[N][M];
vector<ship> myShips;
int max_resistance;
int current_resistance;
int speed;
int reserve_treasure;
char symbol;
public:
ship(int x_, int y_, int max_res, int cur_res, int res_treas, int sp, char sy, map (&myArr)[N] [M], vector<ship> &Ship)
:x(x_)
,y(y_)
,max_resistance(max_res)
,current_resistance(cur_res)
,reserve_treasure(res_treas)
,speed(sp)
,symbol(sy)
,myArray(myArr)
,myShips(Ship)
{cout << "eimai o 'ship' 2" << endl; }
~ship() {}
int get_x();
int get_y();
float get_max_resistance();
float get_current_resistance();
int get_speed();
float get_reserve_treasure();
char get_symbol();
void set_x(int pos_x);
void set_y(int pos_y);
void set_max_resistance(float maxres);
void set_current_resistance(float curres);
void set_speed(int sp);
void set_reserve_treasure(float restrea);
void set_symbol(char sy);
void movement();
void operation();
};
int ship::get_x(){
return x;
}
int ship::get_y(){
return y;
}
float ship::get_max_resistance(){
return max_resistance;
}
float ship::get_current_resistance(){
return current_resistance;
}
int ship::get_speed(){
return speed;
}
float ship::get_reserve_treasure(){
return reserve_treasure;
}
char ship::get_symbol(){
return symbol;
}
void ship::set_x(int pos_x){
x = pos_x;
}
void ship::set_y(int pos_y){
y = pos_y;
}
void ship::set_max_resistance(float maxres){
max_resistance = maxres;
}
void ship::set_speed(int sp){
speed = sp;
}
void ship::set_current_resistance(float curres){
current_resistance = curres;
}
void ship::set_reserve_treasure(float restrea){
reserve_treasure = restrea;
}
void ship::set_symbol(char sy){
symbol = sy;
}
class pirate : public ship
{
public:
pirate(int posx, int posy, float mr, float cr, float rt, int spe, char sym, map (&Array)[N] [M],vector<ship> &Ship ):ship(posx,posy,mr,cr,rt,spe,sym,Array,Ship){
cout << "eimai o 'pirate' 1" << endl;
// ship(90,90,1,50,'#',Array,Ship) {//vector<vector<map> > Array, vector<vector<ship> > Ship) {}
};
Hope you can help
Looking through this code, did you create a custom definition for map? Otherwise, if you are trying to create an [N][M] array of Map objects, you are missing the type declaration of map. e.g. map<int,string>
If you are trying to use map as a multidimensional array, this is not what std::map is for. Map is a generic container for storing key/value pairs.