Thanks to anyone who will help me with this. I am quite new to C++ and I am doing my best to learn the basics of memory and pointers.
In the following code, my goal is to create a vector of pointers to Objects of class "Node" (each with its own integer value), and to create a class "Graph" which essentially is a pointer to the vector itself and a method to print the integer value of the first node.
To create the vector, I use a function "generate_vec_nodes" (inserted in the Constructor of the "Graph" class) that:
- allocates memory in the heap for the vector
- allocates memory in the heap for each new node
- push_back the new node's pointer in the vector
- return the vector's pointer to the Constructor of the Graph Class, that creates a Graph Object.
My problem is: when it is time to retrieve the integer value of the first node, in the "test" function called in Main, I get a Segmentation Fault. It looks like the memory cannot be accessed. I tried to access the element with "(*P_nodes_vec)[0]" inside the Graph Constructor, just after it is returned after being created, and I can do that.
To me it looks like one between the vector Object or the Node Object is deleted or cannot be accessed, but I really do not understand why. I am creating them in the Heap (so they should not be destroyed), and they should be always accessible by the Graph Class method "test" and/or by the Node Class method "get_node_integer" because the Graph Class is a friend class of Node.
The code is:
#include <iostream>
#include <vector>
class node
{
public:
friend class graph;
// constructor:
node(void){int node_integer = 1;};
// function to set the node_to:
void set_node_integer(int x){node_integer = x;};
// function to get the node_to:
int get_node_integer(){return node_integer;};
//private:
int node_integer;
};
///////////////////////////
// function to generate a vector of pointers to nodes, and to return a pointer to this vector:
std::vector<node*> * generate_vec_nodes()
{
std::vector<node*> * new_P_nodes_vec = new std::vector<node*>;
for(int i = 0 ; i < 169 ; i++)
{
node* next_node = new node();
next_node->set_node_integer(i);
new_P_nodes_vec->push_back(next_node);
};
return new_P_nodes_vec;
};
////////////////////////////
class graph
{
private:
// vector of nodes:
std::vector<node*> * P_nodes_vec;
public:
// constructor:
graph()
{
// create a pointer to a vector of 169 nodes:
std::vector<node*> * P_nodes_vec = generate_vec_nodes();
};
// "test" method:
void test(void)
{
std::cout << "Hello 1" << std::endl;
std::cout << (*P_nodes_vec)[0]->get_node_integer() << std::endl;
std::cout << "Hello 2" << std::endl;
};
};
////////////////////////////
int main()
{
// generate the graph:
graph my_graph = graph();
std::cout << std::endl;
std::cout << std::endl;
my_graph.test();
std::cout << std::endl;
std::cout << std::endl;
std::cout << "End of computations";
std::cout << std::endl;
std::cout << std::endl;
return 0;
};