I'm having trouble understanding how to use dynamic allocation with constructors.
I use in my code a class named graph (which is just a bool 2-d matrix representing the edges between the nodes) with the following constructor/destructor (there others methods, but I dont think it's relevant here) :
class graph{
private:
bool** edges;
int size;
public:
graph(int size = 0):size(size){
edges = new bool*[size];
for (int i = 0; i < size; i++){
edges[i] = new bool[size];
}
}
~graph(){
for(int i = 0; i < size; ++i) {
delete [] edges[i];
}
delete [] edges;
}
//others methods
};
In my main, I want to use dynamic allocation :
int main()
{
int size;
cout << "Enter graph size :" << endl;
cin >> size;
graph g1 = new graph(size);
//some processing code
return 0;
}
Howewer, I get an error on the instantiation (ie new graph(size) ) :
invalid conversion from 'graph*' to 'int' [-fpermissive]
I don't really get what is going wrong, and I'm pretty sure it's a syntax I have already seen in others places.
Actually, I dont really get how memory allocation works with the creation of object.
Here, I use new in my constructor to create the bool 2d-matrix, so it's going to the heap, no ? But if I instanciate the object using the following static instruction : graph g1(const_size);
Then it's not suppose to going to the stack ?
Thank you in advance for your answers.
EDIT
Just one last question :
graph *g1 = new graph(size);
is storing g1 (pointer) on stack, but the object is created on the heap.
graph g1(size);
is creating object on the stack, and g1 is a reference to it.
But in any case, the matrix edges would be on the heap ? Or in the second case it would somehow end on the stack ?