Question

I have no idea how to fix this, below is a really simple class that stores a 2D dynamic array and size into an object (matrix). My problem is that initializing a few of these classes doesn't work UNLESS I call a member function. I narrowed the problem, and it's the destructor that's causing this.

Square_Matrix a;   //works
Square_Matrix b;

.

Square_Matrix a,b; //works
a.Set_Size(5);

.

Square_Matrix a,b; //doesn't work as a lone statement, the above does though

header file:

#include <iostream>
using namespace std;

class Square_Matrix
{
public:
   int **matrix;
   int size;
   Square_Matrix();
   ~Square_Matrix();   //causing the problem
   void Set_Size (int new_size);
}

.cpp file:

#include <iostream>
using namespace std;
#include "Square_Matrix.h"


Square_Matrix::Square_Matrix()
{
    size = 0;
}

Square_Matrix::~Square_Matrix()  //causing the problem
{
    for (int i = 0; i < size; i++){
        delete [] matrix[i];
    }
    delete [] matrix;
}
Was it helpful?

Solution

Your default constructor does not initialize data member matrix. So your program has undefined behaviour.

You could define the destructor and constructor the following way

Square_Matrix::Square_Matrix()
{
    size = 0;
    matrix = nullptr;
}

Or

Square_Matrix::Square_Matrix() : matrix( nullptr ), size( 0 )
{
}

Square_Matrix::~Square_Matrix()  //causing the problem
{
    if ( matrix )
    {
        for (int i = 0; i < size; i++){
            delete [] matrix[i];
        }
        delete [] matrix;
    }
}

Also take into account that you need either define the copy constructor and the copy assignment operator or suppress copying and assigning objects of your class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top