Creating multiple instances of c++ library - c++

I am trying to create multiple instances of a static c++ library I wrote, but I can't create multiple instances of it... When I create two instances and write different data to them, I read the same data from both of the instances. Here is my code:
.cpp file:
// MathFuncsLib.cpp
// compile with: cl /c /EHsc MathFuncsLib.cpp
// post-build command: lib MathFuncsLib.obj
/*
DECLARING VECTORS
|3,6,4|
|9,1,5|
|2,0,2|
|5,3,6|
Should be inputted as:
int a[] = {3,6,4,9,1,5,2,0,2,5,3,6} with x = 3 and y = 4
Inputting training vals:
|0.1 (inp1),0.1 (inp2) ,0.1 (targeted output)| depends on the number of inputs and outputs
|9,1,5|
|2,0,2|
|5,3,6|
*/
//#include "stdafx.h"
#include "vector.h"
#include "iostream"
#define DEBUG
#include <stdexcept>
//using namespace std;
double* vectorLib::arrayPtr;
int vectorLib::x;
int vectorLib::y;
vectorLib::vectorLib(int xInp, int yInp) {
vectorLib::arrayPtr = new double[xInp*yInp];
vectorLib::x = xInp;
vectorLib::y = yInp;
//return 0;
}
double vectorLib::sigmoid(double inp) {
return 1 / (1 + exp(-inp));
}
double* vectorLib::getArrayPtr() {
return vectorLib::arrayPtr;
}
double vectorLib::read(int xInp, int yInp) {
#ifdef DEBUG
if (xInp >= vectorLib::x) {
std::cout << "X_OUT_OF_BOUNDS_VECTOR_READ\n";
while (1);
}
if (yInp >= vectorLib::y) {
std::cout << "X_OUT_OF_BOUNDS_VECTOR_READ\n";
while (1);
}
#endif // DEBUG
return *(arrayPtr + xInp + vectorLib::x*yInp);
}
void vectorLib::write(int xInp, int yInp, double data) {
#ifdef DEBUG
if (xInp >= vectorLib::x) {
std::cout << "X_OUT_OF_BOUNDS_VECTOR_WRITE\n";
while (1);
}
if (yInp >= vectorLib::y) {
std::cout << "X_OUT_OF_BOUNDS_VECTOR_WRITE\n";
while (1);
}
#endif // DEBUG
vectorLib::arrayPtr[xInp + vectorLib::x*yInp] = data;
}
void vectorLib::writeArr(double* inpArr) {
int i;
for (i = 0; i < vectorLib::x*vectorLib::y; i++) {
vectorLib::arrayPtr[i] = *(inpArr + i);
}
}
void vectorLib::sigmoidVect() {
int yy;
int xx;
for (yy = 0; yy < vectorLib::y; yy++) {
for (xx = 0; xx < vectorLib::x; xx++) {
write(xx, yy, sigmoid(read(xx, yy)));
}
}
write(0, vectorLib::y - 1, 1);
}
int vectorLib::getX() {
return vectorLib::x;
}
int vectorLib::getY() {
return vectorLib::y;
}
int vectorLib::totalVectSize() {
return vectorLib::x * vectorLib::y;
}
void vectorLib::printVector() {
int yy;
int xx;
for (yy = 0; yy < y; yy++) {
for (xx = 0; xx < x; xx++) {
std::cout << vectorLib::read(xx, yy);
if (xx + 1 != x) {
std::cout << ",";
}
}
std::cout << "\n";
}
}
vectorLib* vectorLib::vectorMult(vectorLib* vect1, vectorLib* vect2) {
#ifdef DEBUG
if (vect1->getX() != vect2->getY()) {
std::cout << "INPUTS_DONT_MATCH_VECTORMULT\n";
while (1);
}
#endif // DEBUG
vectorLib toRet(vect1->getX(), vect2->getY());
int i;
for (i = 0; i < vect2->getX(); i++) {
int p;
for (p = 0; p < vect1->getY(); p++) {
double tempOut = 0;
int q;
for (q = 0; q < vect1->getX(); q++)
{
tempOut += vect1->read(q, p) * vect2->read(i, q);
}
toRet.write(i, p, tempOut);
}
}
return &toRet;
}
.h file:
//#include "stdafx.h"
using namespace std;
class vectorLib
{
//int x, y;
public:
static double* arrayPtr;
static int x;
static int y;
//Constructor takes x and y of the vector
vectorLib(int xInp, int yInp);
//The pointer to the array that holds all the doubles in the vector
static double* getArrayPtr();
//Read the vector at a specified x and y
static double read(int xInp, int yInp);
//Write one double to a specific location
static void write(int xInp, int yInp, double data);
//Write the array inside the vector class
static void writeArr(double* inpArr);
//Takes sigmoid of whole vector
static void sigmoidVect();
//Returns x of vector
static int getX();
//Returns y of vector
static int getY();
//Returns total size of vector
static int totalVectSize();
//Returns a vector pointer to the multiplication result
static vectorLib* vectorMult(vectorLib* vect1, vectorLib* vect2);
//Prints vector
static void printVector();
private:
static double sigmoid(double inp);
};
Main file:
#define DEBUG
#include "stdafx.h"
#include "vector.h"
#include "iostream"
using namespace std;
int main()
{
vectorLib testVectLol(1, 3);
vectorLib testVect(3, 4);
double vectInp[] = { 1,1,1,
1,1,1,
1,1,1,
1,1,1};
double vectInp2[] = { 0.5,0.5,0.5 };
testVect.writeArr(vectInp);
testVectLol.writeArr(vectInp2);
testVect.printVector();// Both print 0.5, 0.5, 0,5
testVectLol.printVector();// Both print 0.5, 0.5, 0,5
while (1);
return 0;
}
Thanks in advance! I've been struggling with this for hours. I would really appreciate any help!
Jasper

Related

Initialize and declare dynamically multiple variables of random entities in a loop in C++

This is my code:
#include <cstdlib>
#include <ctime>
#include <stdio.h>
#include <vector>
#define ENTITY(A) entity##A
#define ALM(A) alm##A
struct TEntity{
private:
int sumx;
int sumy;
const char * rep;
int m_ix;
int m_iy;
public:
TEntity(int x, int y, int sum_x, int sum_y, const char * txt);
};
TEntity::TEntity(int x, int y, int sum_x, int sum_y, const char * txt) {
m_ix = x;
m_iy = y;
sumx = sum_x;
sumy = sum_y;
rep = txt;
}
class IAlmacenable {
private:
void * element;
public:
IAlmacenable(void * e);
IAlmacenable();
void * getValue();
};
IAlmacenable::IAlmacenable(void *e) {
element = e;
}
IAlmacenable::IAlmacenable() {
element = nullptr;
}
void * IAlmacenable::getValue() {
return element;
}
class TList {
private:
std::vector<IAlmacenable*> elementos;
int position;
public:
TList();
int Size();
int Push(IAlmacenable* psz);
};
TList::TList() {
elementos = std::vector<IAlmacenable*>();
position = 0;
}
int TList::Size() {
return elementos.size();
}
int TList::Push(IAlmacenable* psz) {
int res = 0;
if (elementos.size() >= elementos.max_size()) {
res = -1;
}
else {
elementos.push_back(psz);
}
return res;
}
int main(){
srand(time(NULL));
TList *list = new TList();
//we can put entities in the list and the rest will be filled up to 5
int size = list->Size();
for(int i = size; i<5;i++){
const char c[] = {(rand() % 2 ? 65 + rand() % 25 : 97 + rand() % 25), '\0'};
TEntity ENTITY(i)(rand() % 10, rand() % 10, rand() % 5, rand() % 5, c);
IAlmacenable ALM(i)(&ENTITY(i));
list->Push(&ALM(i));
size++;
}
//do things like printing their value...
delete list;
return 0;
}
I need to create a new variable everytime it run the "TEntity ENTITY(i)" line,
the problem is that it creates the same variable always, I think it is because it creates the variable entityi and therefore it is overwriting on the same variable, besides it seems that the random it generates is always the same number since all entities have the same values ​​in all its parameters. The c variable create a const char * random variable between a-z, A-Z , I don't put the print code because it is unnecessary, so what can I do? Is there any way to dynamically create variables of entities whose values ​​are random?
EDIT
Here is the new code fixed (the macros have been eliminated since they were not necessary and the necessary code has been included to be able to execute it) but there is still the same problem that they are generated with the same parameters (since they are still the same variable):
#include <cstdlib>
#include <ctime>
#include <stdio.h>
#include <vector>
#include <conio.h>
#include <windows.h>
struct TEntity{
private:
int sumx;
int sumy;
const char * rep;
int m_ix;
int m_iy;
public:
TEntity(int x, int y, int sum_x, int sum_y, const char * txt);
void movimiento();
void pinta();
};
TEntity::TEntity(int x, int y, int sum_x, int sum_y, const char * txt) {
m_ix = x;
m_iy = y;
sumx = sum_x;
sumy = sum_y;
rep = txt;
}
void TEntity::movimiento() {
m_ix += sumx;
m_iy += sumy;
}
void TEntity::pinta() {
gotoxy(static_cast<short int>(m_ix), static_cast<short int>(m_iy));
printf("%s", rep);
}
void gotoxy(short int x, short int y)
{
COORD pos = {x, y};
HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(output, pos);
}
void clear()
{
system("cls");
}
class IAlmacenable {
private:
void * element;
public:
IAlmacenable(void * e);
IAlmacenable();
void * getValue();
};
IAlmacenable::IAlmacenable(void *e) {
element = e;
}
IAlmacenable::IAlmacenable() {
element = nullptr;
}
void * IAlmacenable::getValue() {
return element;
}
class TList {
private:
std::vector<IAlmacenable*> elementos;
int position;
public:
TList();
int Size();
int Push(IAlmacenable* psz);
IAlmacenable* First();
IAlmacenable* Next();
};
TList::TList() {
elementos = std::vector<IAlmacenable*>();
position = 0;
}
int TList::Size() {
return elementos.size();
}
int TList::Push(IAlmacenable* psz) {
int res = 0;
if (elementos.size() >= elementos.max_size()) {
res = -1;
}
else {
elementos.push_back(psz);
}
return res;
}
IAlmacenable* TList::First() {
IAlmacenable* res;
if (elementos.empty()) {
res = nullptr;
}
else {
res = elementos.front();
position = 1;
}
return res;
}
IAlmacenable* TList::Next() {
IAlmacenable* res;
if (elementos.empty()) {
res = nullptr;
}
else {
int pos = position;
int size = elementos.size();
if (pos < size) {
res = elementos.at(position);
position++;
}
else {
res = this->First();
}
}
return res;
}
int main(){
srand(time(NULL));
TList *list = new TList();
//we can put entities in the list and the rest will be filled up to 5
int size = list->Size();
for(int i = size; i<5;i++){
const char c[] = {(rand() % 2 ? 65 + rand() % 25 : 97 + rand() % 25), '\0'};
TEntity *entity = new TEntity(rand() % 10, rand() % 10, rand() % 5, rand() % 5, c);
IAlmacenable *alm = new IAlmacenable(entity);
list->Push(alm);
size++;
}
while(true){
clear();
for (int i = 0; i < size; i++) {
reinterpret_cast<TEntity *>(list->Next()->getValue())->pinta();
reinterpret_cast<TEntity *>(list->Next()->getValue())->movimiento();
}
Sleep(2000);
}
delete list;
return 0;
}
There is some confusion here.
Some points:
The macro is not fit-for-purpose, as you already know; you're just creating a variable name entityi each time;
That doesn't matter! The object only exists for the duration of the loop iteration anyway; C++ doesn't let you create multiple objects with the same name at the same time. In fact you can get rid of the entire macro stuff and just call the object entity;
Now that that's out of the way, you're getting repeated results because you're storing a pointer to each iteration of that local variable — on each occasion, that's a dangling pointer to an object that's been destroyed. Don't store dangling pointers!
You can either:
Dynamically allocate the objects that you're adding to the list, or
Store actual objects rather than pointers-to-objects.
Either way, the local-scope name is irrelevant and certainly need not change repeatedly for each loop iteration.

Error invalid new-expression of abstract class type FancyPlayer cpp

i have this code at main.cpp :
#include <iostream>
#include <limits>
#include <conio.h>
#include "Ghost/SmartGhost/SmartGhost.h"
#include "Player/Player.h"
#include "PlayerInfo/PlayerInfo.h"
#include "GameBoard/GameBoard.h"
#include "ManualPlayer/ManualPlayer.h"
#include <vector>
using namespace std;
class Position {
public:
int x;
int y;
Position();
Position(int xo,int yo) {x=xo; y=yo;} };
class FancyPlayer : public Player
{
private: vector<Position> visited; //vector of visited nodes int size[2]; //width and height of maze Position start; vector <Position> path; //last visited node(backtrack) public:
void init(int width,int height,int x,int y) {
size[0]=width;
size[1]=height;
start.x=x; //starting position
start.y=y; visited.push_back(Position(start.x,start.y)); path.push_back(Position(start.x,start.y)); }
bool isValid(char ** ViewAround,int x,int y) {
return (ViewAround[x][y]!='#' && ViewAround[x][y]!='*'); }
bool isvisited(int x,int y){
bool f=false;
for(int i=0;i<visited.size();i++) {
if (visited[i].x==x && visited[i].y==y)
f=true;
} return f; }
int getMove(char** ViewAround) {
if (isValid(ViewAround,1,2) && !isvisited(start.x-1,start.y))
{
visited.push_back(Position(start.x-1,start.y));
path.push_back(Position(start.x-1,start.y));
start.x--;
return 0; }
else if (isValid(ViewAround,3,2) && !isvisited(start.x+1,start.y))
{
visited.push_back(Position(start.x+1,start.y));
path.push_back(Position(start.x+1,start.y));
start.x++;
return 1; } else if (isValid(ViewAround,2,3) && !isvisited(start.x,start.y+1))
{
visited.push_back(Position(start.x,start.y+1));
path.push_back(Position(start.x,start.y+1));
start.y++;
return 2; } else if (isValid(ViewAround,2,1) && !isvisited(start.x,start.y-1))
{
visited.push_back(Position(start.x,start.y-1));
path.push_back(Position(start.x,start.y-1));
start.y--;
return 3; } else
{
if (path[path.size()-1].x<start.x){
path.pop_back();
start.x++;
return 1;
}
if (path[path.size()-1].x>start.x){
path.pop_back();
start.x--;
return 0;
}
if (path[path.size()-1].y<start.y){
path.pop_back();
start.y++;
return 2; }
if (path[path.size()-1].y>start.y){
path.pop_back();
start.y--;
return 3;
}
}
}
std::string getName() { return std::string("mplampla"); }
std::string getId() { return std::string("cs141065"); }
};
int main() {
std::vector<ObjectInfo *> PlayersVector; //vector with players engaged
PlayersVector.push_back(new PlayerInfo(*new FancyPlayer(), 'A')); //Erase the comments to play with keyboard
PlayersVector.push_back(new PlayerInfo(*new StupidPlayer(), 'B')); //Fool Standby player
PlayersVector.push_back(new PlayerInfo(*new StupidPlayer(), 'C')); //Fool Standby player
PlayersVector.push_back(new PlayerInfo(*new StupidPlayer(), 'D')); //Fool Standby player
GameBoard *MainGameObject; //Main Game Object
InfoBoard *ptrToInfoBoard = new InfoBoard();
for (int j = 0; j < PlayersVector.size(); ++j) {
ptrToInfoBoard->addPlayer(*static_cast<PlayerInfo *>(PlayersVector[j]));
}
std::ostringstream he;
std::vector<std::string>*ptr = GameBoard::getMapFileNames(DEVCPP_PATH);
for (unsigned int i = 0; i < ptr->size(); ++i) {
he<<DEVCPP_PATH<<ptr->operator[](i);
for (int j = 0; j < EATCH_MAP_PLAY_TIMES; ++j) {
MainGameObject=new GameBoard(true,he.str().c_str(),PlayersVector,EXETASI_MODE,ptrToInfoBoard);
MainGameObject->StartGame();
delete(MainGameObject);
getchar();
}
he.str("");
}
while(1); }
Player.h code :
#ifndef GHOST_PLAYER_H
#define GHOST_PLAYER_H
#include <iostream>
#include <windows.h>
class Player{
private:
public:
Player(){}
virtual std::string getName()=0 ;
virtual std::string getId()=0 ;
virtual int getMove(const char **ViewAround)=0;
virtual void init(int width,int height,int CurrentX,int CurrentY )=0;
};
#endif //GHOST_PLAYER_H
When i am putting at main the
*new FancyPlayer(), 'A')) i am getting an error that telling "[Error] invalid new-expression of abstract class type 'FancyPlayer'" , if i put this line in comment the code works properly...
the stupidplayer code :
StupidPlayer.h :
#ifndef GHOST_STUPIDPLAYER_H
#define GHOST_STUPIDPLAYER_H
#include "../Player/Player.h"
#include "../Move.h"
class StupidPlayer: public Player {
int getMove(const char **ViewAround);
void init(int width,int height,int x,int y);
std::string getName();
std::string getId();
};
#endif //GHOST_STUPIDPLAYER_H
StupidPlayer.cpp :
#include <cstdlib>
#include "StupidPlayer.h"
#include <fstream>
int StupidPlayer::getMove(const char **ViewAround) {
std::ofstream he("inner.txt");
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
he<<ViewAround[i][j];
}
he<<'\n';
}
return STAND;
}
void StupidPlayer::init(int width, int height, int x, int y) {
}
std::string StupidPlayer::getName() {
return std::string("StupidPlayer");
}
std::string StupidPlayer::getId() {
return std::string("cs161119");
}
i cant see any difference between stupidplayer and fancy... what can i do... in order to make fancy works properly... it may be a problem that have 2 classes in use for fancy?

Calculate car movement and distance with C++ classes

This program compiles however, I need to get this function to move on the x & y coordinate and then output the total distance traveled. The xCord moves it right and left while the yCord moves it up and down. I think I need to update my int Taxicab::getDistanceTraveled(), void Taxicab::moveX(int getX), & void Taxicab::moveX(int getX). But for the life of me can't figure out what to do to get it to update properly. When I compile and run it gives me 132617596 for cab1 distance travelled and 0 for the Y coordinate on cab2. Thanks for the help!
#ifndef TAXI_CPP
#define TAXI_CPP
class Taxicab
{
private:
int xCord;
int yCord;
int totalDist;
public:
Taxicab(); //default constructor
Taxicab(int, int); //overload constructor
int getX(); //returns X coordinate
int getY(); //returns Y coordinate
int getDistanceTraveled(); //returns distance calculation
void moveX(int); //moves X left or right
void moveY(int); //moves Y left or right
};
#endif // !TAXI_CPP
#include "Taxi.h"
#include <iostream>
#include <math.h>
#include <cstdlib>
using std::cout;
using std::cin;
using std::endl;
using std::abs;
Taxicab::Taxicab() //default constructor
{
}
Taxicab::Taxicab(int xCord, int yCord) //overload constructor
{
xCord = 0; //initialize to 0
yCord = 0; //initialize to 0
totalDist = 0; //initialize to 0
}
int Taxicab::getX()
{
return xCord; //return x coordinate
}
int Taxicab::getY()
{
return yCord; //return y coordinate
}
void Taxicab::moveX(int getX)
{
int moveX = 0;
moveX = moveX + getX;
}
void Taxicab::moveY(int getY)
{
int moveY = 0;
moveY = moveY + getY;
}
int Taxicab::getDistanceTraveled()
{
return abs(xCord) + abs(yCord);
}
#include <iostream>
#include "Taxi.h"
#include <math.h>
using std::cout;
using std::cin;
using std::endl;
int main()
{
Taxicab cab1;
Taxicab cab2(5, -8);
cab1.moveX(3);
cab1.moveY(-4);
cab1.moveX(-1);
cout << cab1.getDistanceTraveled() << endl;
cab2.moveY(7);
cout << cab2.getY() << endl;
}
Your constructors do not make sense.
In default constructor you have to initialize member variables to something, otherwise their values are undefined and could be set to some random value. Try these maybe:
Taxicab::Taxicab() //default constructor
{
xCord = 0; //initialize to 0
yCord = 0; //initialize to 0
totalDist = 0; //initialize to 0
}
Taxicab::Taxicab(int xCord, int yCord) //overload constructor
{
this->xCord = xCord;
this->yCord = yCord;
totalDist = 0; //initialize to 0
}
Methods to move taxi also do not make much sense. Maybe something like that would be better:
void Taxicab::moveX(int offsetX)
{
totalDist += abs(offsetX);
xCoord += offsetX;
}
void Taxicab::moveY(int offsetY)
{
totalDist += abs(offsetY);
yCoord += offsetY;
}
int Taxicab::getDistanceTraveled()
{
return totalDist;
}

Unable to read memory for object array deletion

So I am testing out some object arrays in C++, and I am trying to delete these objects afterwards, as I am supposed to.
But here's the problem: the deleteInputPattern variable works fine, so I am able to fully delete "inputs" within the CSVFile header class, but its equivalent in the main file, "inputArray", triggers a breakpoint.
What is the problem here? Am I trying to delete non-existent memory? Do any of the pointers need
Code wall below:
InputTest.h:
#pragma once
class InputTest
{
private:
float r;
float g;
float b;
float t;
public:
InputTest();
~InputTest();
InputTest(float r, float g, float b, float t);
void setR(float newT);
float getR();
void setG(float newT);
float getG();
void setB(float newT);
float getB();
void setT(float newT);
float getT();
void print(int count);
};
InputTest.cpp:
#include "InputTest.h"
#include <stdio.h>
InputTest::InputTest()
{
printf("Input constructor\n");
}
InputTest::~InputTest()
{
printf("Input destructor\n");
}
InputTest::InputTest(float r, float g, float b, float t)
{
this->r = r;
this->g = g;
this->b = b;
this->t = t;
}
void InputTest::setR(float newT)
{
r = newT;
}
float InputTest::getR()
{
return r;
}
void InputTest::setG(float newT)
{
g = newT;
}
float InputTest::getG()
{
return g;
}
void InputTest::setB(float newT)
{
b = newT;
}
float InputTest::getB()
{
return b;
}
void InputTest::setT(float newT)
{
t = newT;
}
float InputTest::getT()
{
return t;
}
void InputTest::print(int count)
{
printf("R: %.2f\n", r);
printf("G: %.2f\n", g);
printf("B: %.2f\n", b);
printf("T: %.2f\n", t);
}
Copy.h:
#pragma once
class InputTest;
class Copy
{
private:
int patternCount;
InputTest** inputs;
public:
Copy();
~Copy();
InputTest* getInputPattern(int index);
void addInputPattern(InputTest* in);
void deleteInputPattern();
};
Copy.cpp:
#include "Copy.h"
#include "InputTest.h"
#include <string.h>
#include <stdio.h>
Copy::Copy()
{
printf("CSV File constructor\n");
inputs = NULL;
patternCount = 0;
inputs = new InputTest*[3];
int i;
for (i = 0; i < 3; i++)
{
inputs[i] = new InputTest();
}
}
Copy::~Copy()
{
printf("CSV File destructor\n");
}
InputTest * Copy::getInputPattern(int index)
{
printf("input gotten: %d\n", index);
return inputs[index];
}
void Copy::addInputPattern(InputTest * in)
{
inputs[patternCount] = in;
patternCount++;
printf("input added: %d\n", patternCount);
}
void Copy::deleteInputPattern()
{
int i;
for (i = 0; i < patternCount; i++)
{
delete inputs[i];
}
delete inputs;
inputs = NULL;
}
main.cpp:
#include "Copy.h"
#include "InputTest.h"
#include <string.h>
#include <stdio.h>
int main(int argv, char** argc)
{
bool testResult = false;
Copy *test = NULL;
test = new Copy();
InputTest **inputArray;
inputArray = new InputTest*[3];
int count;
for (count = 0; count < 3; count++)
{
inputArray[count] = new InputTest();
inputArray[count]->setR(0.2f);
inputArray[count]->setG(0.6f);
inputArray[count]->setB(0.8f);
inputArray[count]->setT(0.5f);
test->addInputPattern(inputArray[count]);
inputArray[count] = test->getInputPattern(count);
printf("next\n");
}
for (count = 0; count < 3; count++)
{
printf("round %d\n", count);
printf("R: %f\n", inputArray[count]->getR());
printf("G: %f\n", inputArray[count]->getG());
printf("B: %f\n", inputArray[count]->getB());
printf("T: %f\n", inputArray[count]->getT());
}
test->deleteInputPattern();
for (count = 0; count < 3; count++)
{
delete inputArray[count];
}
delete inputArray;
delete test;
inputArray = NULL;
test = NULL;
return testResult;
}
These seem to be the problematic line:
test->deleteInputPattern();
for (count = 0; count < 3; count++)
{
delete inputArray[count];
}
Since you have already deleted using test->deleteInputPattern(), that memory is freed. Now you are deleting the same objects (to which you are still holding a reference via inputArray) explicitly in main using delete inputArray. But that memory is already deleted in deleteInputPattern and hence you should be getting a memory access error.
You need to free any allocated memory only once. There is no need to do it again in main(). Either call deleteInputPattern or call delete explicitly in main, but not both. I can recommend 2 best practices:
Use smart pointers
The allocating module should delete the memory (this may not be applicable in many situations though such as factories)

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.