Deep copy unsuccessful - c++

might be a stupid question and if it is, let me know, I will delete it as soon as possible. The thing is I have to make a deep copy in class "Kambarys" (ignore mixed languages, I know I shouldn't do that). Program terminates after trying to call function second time. Probably the problem is my syntax in constructor copy, but I can't find the correct one anywhere. One of the requirements is to create langas, durys and kambarys in dynamic memory using "new" and delete windows vector and door in Kambarys destructor. Appreciate the help!
Requirements:
In the main method, use the new operator to create room k1, add windows and doors to it. Write a constructor Room (const Room & k) that would create a correct copy. In the method main, write another room k2. Calculate the length of the baseboards / wall area.
Perform the following steps: k2 = * k1; delete k1;
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
class Langas{
private:
float height;
float widht;
static int countL;
public:
Langas(float h, float w){
this->height=h;
this->widht=w;
countL++;
}
~Langas(){
--countL;
}
float getHeight(){
return height;
}
float getWidht(){
return widht;
}
static int getWindowCount(){
return countL;
}
};
class Durys{
private:
float heightD;
float widhtD;
static int countD;
public:
Durys(float hD, float wD){
this->heightD=hD;
this->widhtD=wD;
countD++;
}
~Durys(){
--countD;
}
float getHeightD(){
return heightD;
}
float getWidhtD(){
return widhtD;
}
static int getDoorCount(){
return countD;
}
};
class Kambarys{
private:
float heightK;
float widhtK;
float lenghtK;
public:
vector<Langas*> windows;
Durys* door;
Kambarys(float hK, float wK, float lK){
this->heightK=hK;
this->widhtK=wK;
this->lenghtK=lK;
}
Kambarys(const Kambarys &k){
this->door=k.door;
this->windows=k.windows;
heightK=k.heightK;
widhtK=k.widhtK;
lenghtK=k.lenghtK;
}
~Kambarys(){
door=NULL;
for(int i=0; i<windows.size(); i++){
delete windows[i];
}
windows.clear();
delete door;
}
float getHeightK(){
return heightK;
}
float getWidhtK(){
return widhtK;
}
float getLenghtK(){
return lenghtK;
}
void addWindow(Langas* w){
windows.push_back(w);
}
void addDoor(Durys *d){
door=d;
}
};
float countWallPlot(Kambarys* k){
float cWPlot=(2*k->getLenghtK()*k->getHeightK())+(2*k->getWidhtK()*k->getHeightK());
for(int i=0; i<k->windows.size(); i++){
cWPlot-=((k->windows[i]->getHeight()))*(k->windows[i]->getWidht());
}
cWPlot-=((k->door->getHeightD()))*(k->door->getWidhtD());
return cWPlot;
}
float countLenght(Kambarys* k){
float floorL=(k->getLenghtK()*k->getWidhtK()*2);
floorL-=(k->door->getWidhtD());
return floorL;
}
int Langas::countL=0;
int Durys::countD=0;
int main(){
Langas *langas1=new Langas(3.4, 1.2);
Durys *durys=new Durys(3.1, 1.5);
Langas *langas2=new Langas(6.4, 1.5);
Kambarys *k=new Kambarys(30.4, 40.1, 50.1);
Kambarys *k2=k;
k->addWindow(langas1);
k->addWindow(langas2);
k->addDoor(durys);
cout<<countWallPlot(k)<<" "<<countLenght(k)<<endl;
cout<<"Window count "<<Langas::getWindowCount()<<", door count "<<Durys::getDoorCount()<<endl;
k2=k;
delete k;
cout<<countWallPlot(k2)<<" "<<countLenght(k2)<<endl;
cout<<"Window count "<<Langas::getWindowCount()<<", door count "<<Durys::getDoorCount()<<endl;
}

You have to allocate memory for k2 and copy the object, not the pointer.
You have to allocate memory in the copy constructor and copy assignment operator.
door=NULL; before delete door; would skip the delete and cause a memory leak.
windows.clear(); is not necessary in the destructor. Keep your code simple.
EDIT: After you added "Perform the following steps: k2 = * k1; delete k1;" I made k2 an object, not a pointer.
#include <iostream>
#include <vector>
class Langas {
private:
float height;
float width;
static int count;
public:
Langas(float h, float w): height(h), width(w) {
++count;
}
~Langas() { --count; }
float getHeight() const { return height; }
float getWidht() const { return width; }
static int getWindowCount() { return count; }
};
class Durys {
private:
float height;
float width;
static int count;
public:
Durys(float h, float w): height(h), width(w) {
++count;
}
~Durys() { --count; }
float getHeight() const { return height; }
float getWidth() const { return width; }
static int getDoorCount() { return count; }
};
class Kambarys {
private:
float height;
float width;
float length;
public:
std::vector<Langas *> windows;
Durys *door = nullptr;
Kambarys(float hK, float wK, float lK): height(hK), width(wK), length(lK) {}
Kambarys(const Kambarys &k): height(k.height), width(k.width), length(k.length), windows(), door(k.door ? new Durys(k.door->getHeight(), k.door->getWidth()) : nullptr) {
for (const auto window : k.windows) {
windows.emplace_back(new Langas(window->getHeight(), window->getWidht()));
}
}
Kambarys &operator=(const Kambarys &k) {
door = k.door ? new Durys(k.door->getHeight(), k.door->getWidth()) : nullptr;
for (const auto window : k.windows) {
windows.emplace_back(new Langas(window->getHeight(), window->getWidht()));
}
height = k.height;
width = k.width;
length = k.length;
return *this;
}
~Kambarys() {
for (auto window : windows) {
delete window;
}
delete door;
}
float getHeight() const { return height; }
float getWidth() const { return width; }
float getLength() const { return length; }
void addWindow(Langas *w) { windows.emplace_back(w); }
void addDoor(Durys *d) { door = d; }
};
float countWallPlot(const Kambarys &k) {
float cWPlot = 2 * k.getLength() * k.getHeight() + 2 * k.getWidth() * k.getHeight();
for (const auto window : k.windows) {
cWPlot -= window->getHeight() * window->getWidht();
}
cWPlot -= k.door->getHeight() * k.door->getWidth();
return cWPlot;
}
float countLength(const Kambarys &k) {
float floor = k.getLength() * k.getWidth() * 2;
floor -= k.door->getWidth();
return floor;
}
int Langas::count = 0;
int Durys::count = 0;
int main() {
Langas *langas1 = new Langas(3.4, 1.2);
Durys *durys = new Durys(3.1, 1.5);
Langas *langas2 = new Langas(6.4, 1.5);
Kambarys *k = new Kambarys(30.4, 40.1, 50.1);
Kambarys k2(*k);
k->addWindow(langas1);
k->addWindow(langas2);
k->addDoor(durys);
std::cout << countWallPlot(*k) << " " << countLength(*k) << std::endl;
k2 = *k;
std::cout << "Window count " << Langas::getWindowCount() << ", door count " << Durys::getDoorCount() << std::endl;
delete k;
std::cout << countWallPlot(k2) << " " << countLength(k2) << std::endl;
std::cout << "Window count " << Langas::getWindowCount() << ", door count " << Durys::getDoorCount() << std::endl;
}

Related

C++ pointer syntax in class constructor leading to malloc error

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

C++ Inheritance is not working properly

#include <iostream>
using namespace std;
class Item {
private:
int _code;
int _color;
int _brand;
double _height;
double _length;
double _width;
double _weight;
double _price;
int _type;
bool _doesItHaveThis;
public:
Item();
Item(int code, int color, int brand, double height, double length, double width,
double weight, double price, int type, bool doesItHaveThis);
void setCode(int code);
void setColor(int color);
void setBrand(int brand);
void setHeight(double height);
void setLength(double length);
void setWidth(double width);
void setWeight(double weight);
void setPrice(double price);
void setType(int type);
void setDoesItHaveThis(bool doesItHaveThis);
int getCode();
int getColor();
int getBrand();
double getHeight();
double getLength();
double getWidth();
double getWeight();
double getPrice();
int getType();
bool getDoesItHaveThis();
virtual ~Item();
void display();
};
//----------------------------------------------------------
Item::Item()
{
_code = 0;
_color = 0;
_brand = 0;
_height = 0;
_length = 0;
_width = 0;
_weight = 0;
_price = 0;
_type = 0;
_doesItHaveThis = 0;
}
//----------------------------------------------------------
Item::Item(int code, int color, int brand, double height, double length, double width,
double weight, double price, int type, bool doesItHaveThis)
{
_code = code;
_color = color;
_brand = brand;
_height = height;
_length = length;
_width = width;
_weight = weight;
_price = price;
_type = type;
_doesItHaveThis = doesItHaveThis;
}
//----------------------------------------------------------
void Item::setCode(int code)
{
_code = code;
}
//----------------------------------------------------------
void Item::setColor(int color)
{
_color = color;
}
//----------------------------------------------------------
void Item::setBrand(int brand)
{
_brand = brand;
}
//----------------------------------------------------------
void Item::setHeight(double height)
{
_height = height;
}
//----------------------------------------------------------
void Item::setLength(double length)
{
_length = length;
}
//----------------------------------------------------------
void Item::setWidth(double width)
{
_width = width;
}
//----------------------------------------------------------
void Item::setWeight(double weight)
{
_weight = weight;
}
//----------------------------------------------------------
void Item::setPrice(double price)
{
_price = price;
}
//----------------------------------------------------------
void Item::setType(int type)
{
_type = type;
}
//----------------------------------------------------------
void Item::setDoesItHaveThis(bool doesItHaveThis)
{
_doesItHaveThis = doesItHaveThis;
}
//----------------------------------------------------------
int Item::getCode()
{
return _code;
}
//----------------------------------------------------------
int Item::getColor()
{
return _color;
}
//----------------------------------------------------------
int Item::getBrand()
{
return _brand;
}
//----------------------------------------------------------
double Item::getHeight()
{
return _height;
}
//----------------------------------------------------------
double Item::getLength()
{
return _length;
}
//----------------------------------------------------------
double Item::getWidth()
{
return _width;
}
//----------------------------------------------------------
double Item::getWeight()
{
return _weight;
}
//----------------------------------------------------------
double Item::getPrice()
{
return _price;
}
//----------------------------------------------------------
int Item::getType()
{
return _type;
}
//----------------------------------------------------------
bool Item::getDoesItHaveThis()
{
return _doesItHaveThis;
}
//----------------------------------------------------------
Item::~Item()
{
cout << "ITEM ELIMINATED" << endl;
}
//----------------------------------------------------------
void Item::display()
{
cout << "code = " << _code << ", color = " << _color << ", brand = "
<< _brand << ", height = " << _height << ", length = " << _length
<< ", width = " << _width << ", weight = " << _weight << ", price = "
<< _price << ", type = " << _type << ", doesItHaveThis = "
<< _doesItHaveThis << endl;
}
//----------------------------------------------------------
class Pens : public Item {
private:
int _code;
int _color;
int _brand;
double _height;
double _length;
double _width;
double _weight;
double _price;
int _type;
bool _doesItHaveThis;
int _packetSize;
public:
Pens();
Pens(int code, int color, int brand, double height, double length, double width,
double weight, double price, int type, bool doesItHaveThis, int packetSize);
void setPacketSize(int packetSize);
int getPacketSize();
virtual ~Pens();
void display();
};
//----------------------------------------------------------
Pens::Pens()
{
_code = 0;
_color = 0;
_brand = 0;
_height = 0;
_length = 0;
_width = 0;
_weight = 0;
_price = 0;
_type = 0;
_doesItHaveThis = 0;
_packetSize = 0;
}
//----------------------------------------------------------
Pens::Pens(int code, int color, int brand, double height, double length, double width,
double weight, double price, int type, bool doesItHaveThis, int packetSize)
{
_code = code;
_color = color;
_brand = brand;
_height = height;
_length = length;
_width = width;
_weight = weight;
_price = price;
_type = type;
_doesItHaveThis = doesItHaveThis;
_packetSize = packetSize;
}
//----------------------------------------------------------
void Pens::setPacketSize(int packetSize)
{
_packetSize = packetSize;
}
//----------------------------------------------------------
int Pens::getPacketSize()
{
return _packetSize;
}
//----------------------------------------------------------
Pens::~Pens()
{
cout << "PEN ELIMINATED" << endl;
}
//----------------------------------------------------------
void Pens::display()
{
cout << "code = " << _code << ", color = " << _color << ", brand = "
<< _brand << ", height = " << _height << ", length = " << _length
<< ", width = " << _width << ", weight = " << _weight << ", price = "
<< _price << ", type = " << _type << ", doesItHaveThis = "
<< _doesItHaveThis << ", packetSize = " << _packetSize << endl;
}
//----------------------------------------------------------
void main()
{
Pens I1(1, 2, 3, 4.1, 2.0, 3.4, 3.3, 3.2, 5, 1, 0);
I1.setBrand(999);
I1.setDoesItHaveThis(0);
I1.setHeight(34.62);
I1.display();
}
So this is my code, and I'm wondering why the Pens class is not properly inheriting the public methods of the Item class. When I run this code, the setBrand(999), setDoesItHaveThis, and setHeight don't work from what I can tell from the output. Can anybody tell what I did wrong?
The way to use polymorphism is to inherit the members of the base class. If you repeat them instead, then this will declare another member of the same name.
struct base
{
int member1 = 0; // the =0 means that these members
int member2 = 0; // will be default initialised to 0
base() = default;
explicit base(int i, int j=0)
: member1(i), member2(j) {}
};
struct derived
: base
{
int member1 = 1; // not to be confused with base::member1
int member3 = 4;
derived() = default;
explicit derived(int i, int j=0, int k=1, int m=4)
: base(i,j), member1(k), member3(m) {}
int foo() const
{ return member1 * base::member1; }
};
Here, derived has two members member1: one inherited from base and another not inherited. These two can be easily confused by a programmer (but not by the compiler). So such constructs should be avoided (and good compilers will warn you).
In the derived class call the base class constructor with all the arguments you need. And like pointed out in the comments do not redeclare all the base class variables as new members of the derived class. To set/get the base class member variables use the Setters and Getters that you have made public in your base class (these get inherited by the derived class). (Although I would make the setters protected if I were you). Also look in to initializer lists in constructors instead of initializing each member in the body - Read this

Why does my vector of pointers keep on resulting in a EXC_BAD_ACCESS?

I am attempting to create a graphical representation of finite automata using xcode, and as such I have created classes for states and transitions. In order to make moving objects easy, I have included a collection of pointers of transitions going in and out of the state. Compiling is fines, but when I try to append to the vector, it produces the following error. EXC_BAD_ACCESS(code=1, address=0x3f35)
Following the error takes me to the std library, and shows the error being in this line.
template <class _Tp, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
void
vector<_Tp, _Allocator>::push_back(const_reference __x)
{
if (this->__end_ != this->__end_cap())
{
__annotate_increase(1);
__alloc_traits::construct(this->__alloc(),
_VSTD::__to_raw_pointer(this->__end_), __x);
++this->__end_;
}
else
__push_back_slow_path(__x);
}
Here is a simplified version of my State class, my Transition class is declared before and is then defined afterwards.
class State
{
int id;
std::vector<Transition *> links_in;
std::vector<Transition *> links_out;
float x;
float y;
int r = radius; //x, y are centre coordinates of the circle representing the state, while r is the radius
bool is_active = false;
bool is_end = false;
bool is_shown = true;
bool is_moving;
public:
// Get Functions go here
// Set Functions go here
//Add functions
void add_in_trans(Transition * t){
links_in.push_back(t);
}
void add_out_trans(Transition * t){
links_out.push_back(t);
}
//Delete Functions
void remove_in_trans(){
links_in.pop_back();
}
void remove_out_trans(){
links_out.pop_back();
}
void draw_state();
State(int ix, int iy);
State(){}
}
If you have any suggestions for a better way of doing this, I am more then happy to hear them. I have spent all day trying to sort this out, to no avail.
Thanks in advance.
UPDATE:
I attempted to use integers and vectors as a temporary fix, but I came up with the same problem, so I assume that the problem isn't the pointers but the way I'm using vectors.
This is the code
#include <vector>
class Transition;
class State
{
int id;
std::vector<int> links_in;
std::vector<int> links_out;
float x;
float y;
int r = radius; //x, y are centre coordinates of the circle representing the state, while r is the radius
bool is_active = false;
bool is_end = false;
bool is_shown = true;
bool is_moving;
public:
// Get Functions
int get_x(){
return x;
}
int get_y(){
return y;
}
int get_id(){
return id;
}
bool is_it_active(){
return is_active;
}
bool is_it_moving(){
return is_moving;
}
bool is_in(int ix, int iy){ //Function to tell if pair of coordinates are in the circle, used to select.
std::cerr << ix-x << " " << iy-y << " " << r*r << std::endl;
if ((ix-x)*(ix-x) + (iy-y)*(iy-y) < r*r)
return true;
else
return false;
}
// Set Functions
void set_active(bool s){
is_active = s;
}
void set_moving(bool s){
is_moving = s;
}
void end_switch(){
is_end = !is_end;
}
void set_start(){
g_start_state = id;
}
void set_x(int ix){
x = ix;
}
void set_y(int iy){
y = iy;
}
//Add functions
void add_in_trans(int t){
links_in.push_back(t);
}
void add_out_trans(int t){
links_out.push_back(t);
}
//Delete Functions
void remove_in_trans(){
links_in.pop_back();
}
void remove_out_trans(){
links_out.pop_back();
}
void draw_state();
State(int ix, int iy);
State(){}
};
State::State(int ix, int iy){
id = g_state_num;
if (g_start_state == 0)
g_start_state = id;
x = ix;
y = iy;
}
void State::draw_state(){
if (is_shown){
if (is_moving)
glTranslatef(g_cursor_x, g_cursor_y, 0.0);
else
glTranslatef(x, y, 0.0);
fill_colour();
if (is_active)
active_fill_colour();
glBegin(GL_POLYGON);
for (size_t i=0; i<24; i++){
float n[2] = {static_cast<float>(r * cos(i*6)), static_cast<float>(r * sin(i*6))};
glVertex2fv(n);
}
glEnd();
line_colour();
glBegin(GL_LINES);
for (size_t i=0; i<24; i++){
float n[2] = {static_cast<float>(r * cos(i*6)), static_cast<float>(r * sin(i*6))};
glVertex2fv(n);
}
glEnd();
if(is_end){
glPushMatrix();
glScalef(0.9, 0.9, 0.9);
for (size_t i=0; i<24; i++){
float n[2] = {static_cast<float>(r * cos(i*6)), static_cast<float>(r * sin(i*6))};
glVertex2fv(n);
}
glPopMatrix();
}
text_colour();
std::string s = std::to_string(id);
for (int i=0; i<s.length(); i++){
glPushMatrix();
glTranslatef(-radius/2 + i*kerning, -radius/2, 0.0);
glScalef(0.3, 0.3, 1.0);
glutStrokeCharacter(GLUT_STROKE_ROMAN, s[i]);
glPopMatrix();
}
}
}
class Character{
int id;
char c;
public:
int get_id(){
return id;
}
char get_char(){
return c;
}
void set_char(char ic){
c = ic;
}
Character(char ic);
Character(){};
};
Character::Character(char ic){
id = g_character_num;
g_character_num++;
c = ic;
}
class Transition{
int ident;
State * from_state;
State * to_state;
float from[2];
float to[2];
Character c;
public:
void set_from(float x, float y){
from[0] = x;
from[1] = y;
}
void set_to(float x, float y){
to[0] = x;
to[1] = y;
}
void set_char(Character ic){
c = ic;
}
int get_id(){
return ident;
}
void draw_trans();
void set_trans(State * ifrom, State * ito, Character ic){
from_state = ifrom;
to_state = ito;
from[0] = ifrom->get_x();
from[1] = ifrom->get_y();
to[0] = ito->get_x();
to[1] = ito->get_y();
c = ic;
}
Transition(){};
Transition(State ifrom, State ito, Character ic){
from_state = &ifrom;
to_state = &ito;
from[0] = ifrom.get_x();
from[1] = ifrom.get_y();
to[0] = ito.get_x();
to[1] = ito.get_y();
c = ic;
}
};
void Transition::draw_trans(){
line_colour();
glBegin(GL_LINES);
glVertex2fv(from);
glVertex2fv(to);
glEnd();
float grad = (from[0] - to[0]) /(from[1] - to[1]); //(By finding the gradient of the slope, we can fin good place to show it's information, it's character.
if (grad < -1 || grad > 1){
glPushMatrix();
glTranslatef(from[0] - to[0] - 20, from[1] - to[1], 1.0);
}
else{
glPushMatrix();
glTranslatef(from[0] - to[0], from[1] - to[1] + 20, 1.0);
}
glutStrokeCharacter(GLUT_STROKE_ROMAN, (c.get_char()));
glPopMatrix();
}

My object is being destructed right after being constructed

I'm trying to construct a two-dimensional boolean array with a class I've created called Grid. The Grid object is a private member class of another class called GameOfLife. Whenever I create a GameOfLife object with the parameters belove, the Grid object first gets created with the default constructor, then it gets created again with the constructor with parameters, and then for some reason Grid's deconstructor runs and deletes everything ? I'm really out of ideas :p I'm running MinGW GCC on Eclipse Luna.
Main.cpp
const int HEIGHT = 25;
const int WIDTH = 25;
#include <iostream>
#include "GameOfLife.h"
int main(int argc, const char * argv[]) {
GameOfLife game = GameOfLife(HEIGHT, WIDTH, false);
game.play();
return 0;
}
Grid.h
#ifndef __Game_Of_Life__Grid__
#define __Game_Of_Life__Grid__
#include <stdio.h>
class Grid {
public:
Grid(int y, int x, bool state);
Grid();
void allocate(int x, int y, bool state);
void deallocate();
void set(int x, int y, bool state);
bool get(int x, int y);
void setAll(bool state);
void switchBoards();
~Grid();
private:
bool ** oldGeneration;
bool ** newGeneration;
int height;
int width;
};
#endif /* defined(__Game_Of_Life__Grid__) */
Grid.cpp
#include "Grid.h"
Grid::Grid(int y, int x, bool state) {
allocate(x, y, state);
}
void Grid::allocate(int x, int y, bool state) {
height = y;
width = x;
oldGeneration = new bool*[height];
newGeneration = new bool*[height];
for (int i = 0; i < height; i++) {
oldGeneration[i] = new bool[width];
newGeneration[i] = new bool[width];
}
}
Grid::~Grid() {
deallocate();
}
void Grid::switchBoards() {
bool ** temp = oldGeneration;
oldGeneration = newGeneration;
newGeneration = temp;
delete temp;
}
bool Grid::get(int x, int y) {
return oldGeneration[y][x];
}
void Grid::set(int x, int y, bool state) {
newGeneration[y][x] = state;
}
void Grid::deallocate() {
if (oldGeneration != NULL || newGeneration != NULL) {
for (int i = 0; i < height; i++) {
delete [] oldGeneration[i];
delete [] newGeneration[i];
}
delete [] oldGeneration;
delete [] newGeneration;
}
return;
}
Grid::Grid() {
oldGeneration = NULL;
newGeneration = NULL;
width = 0;
height = 0;
}
void Grid::setAll(bool state) {
for (int i = 0; i < height; i++) {
for (int n = 0; n < width; n++) {
newGeneration[i][n] = state;
}
}
}
GameOfLife.h
#ifndef __Game_Of_Life__GameOfLife__
#define __Game_Of_Life__GameOfLife__
#include <stdio.h>
#include "Grid.h"
#include <iostream>
class GameOfLife {
private:
Grid board;
public:
GameOfLife(int y, int x, bool state);
GameOfLife();
~GameOfLife();
void play();
void welcome();
void makeBoard();
void updateBoard();
int findAliveNeighbours(int x, int y);
};
#endif /* defined(__Conway__GameOfLife__) */
GameOfLife.cpp
#include "GameOfLife.h"
const int WIDTH = 100;
const int HEIGHT= 75;
GameOfLife::GameOfLife(int y, int x, bool state) {
board = Grid(y, x, state);
}
GameOfLife::GameOfLife() {
board = Grid();
}
GameOfLife::~GameOfLife() {
board.deallocate();
}
void GameOfLife::play() {
welcome();
makeBoard();
for (int i = 0; i < HEIGHT; i++) {
for (int n = 0; n < WIDTH; n++) {
std::cout << board.get(n,i) << " ";
}
std::cout << std::endl;
}
updateBoard();
std::cout << std::endl;
for (int i = 0; i < HEIGHT; i++) {
for (int n = 0; n < WIDTH; n++) {
std::cout << board.get(n,i) << " ";
}
std::cout << std::endl;
}
}
void GameOfLife::makeBoard() {
int x1,x2,x3,x4, y1,y2,y3,y4;
x1 = 10; y1 = 10;
x2 = 10; y2 = 11;
x3 = 10; y3 = 12;
x4 = 11; y4 = 13;
int x5 = 0; int y5 = 0;
board.set(x1, y1, true);
board.set(x2, y2, true);
board.set(x3, y3, true);
board.set(x4, y4, true);
board.set(x5, y5, true);
}
void GameOfLife::welcome() {
std::cout << "Welcome to Conway's Game Of Life"
<< std::endl;
}
GameOfLife::GameOfLife(int y, int x, bool state) {
// board is a member variable that gets initialized
// with the default constructor.
// Then it gets replaced by assignment with a different
// Grid object. The temporary object gets deleted at
// the end of the line.
board = Grid(y, x, state);
}
Change the implementation to:
GameOfLife::GameOfLife(int y, int x, bool state) : board(y, x, state) {}
Similarly, change the default constructor to:
GameOfLife::GameOfLife() {}
The more important problem that needs to be fixed is that you are breaking The Rule of Three.
You need to add proper implementations of the copy constructor and the copy assignment opertor in Grid.
The other, and better, option is to change the internal data of Grid to
std::vector<std::vector<bool>> oldGeneration;
std::vector<std::vector<bool>> newGeneration;
Then, the compiler generated copy constructor and copy assignment operator will be good enough.

Error when resizing vector of object

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.