Trying to pass a double pointer of an object into a node of self similar type?

Hello,

The following code compiles and runs fine till it reaches line 16 and gets a sigsev violation which I'm not sure about as to why. I have no problem passing the object of type node** into the constructor of base
and storing it into the double pointer node** copy;; but when I call the function void pass(node** temp) it crashes. I don't expect anyone to fix this but I just want to know why wouldn't this work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>

class base;
class node
{
    private:

        node** data;

    public:

    node(){}
    ~node(){}
    void pass(node** temp)
    {
        this->data = temp;//Step 4 sigsev violation???
    }
};
class base
{
    private:

        node** copy;

    public:

    base(){}
    base( node** temp)
    {
        (this->copy) = new node*();//Step 2 create an object to hold the node.
        (this->copy) = temp;
        (*this->copy)->pass(temp);//Step 3 pass the node from the int main into the new object.
    }
    ~base(){}
};
int main()
{
    node** temp = new node*();//Step 1 create a node of double pointer
    base base_1(temp);//and pass it into the base object.

    return 0;
}

On line 31 you overwrite the pointer to the object you just dynamically allocated.

You never actually create any instances of node, you only create pointers to pointers to it.
On line 31 you overwrite the pointer to the object you just dynamically allocated.

You never actually create any instances of node, you only create pointers to pointers to it.


Ok so if I change this

1
2
3
 (this->copy) = new node*();//Step 2 create an object to hold the node.
        (this->copy) = temp;
        (*this->copy)->pass(temp);//Step 3 pass the node from the int main into the new object. 


to

1
2
3
 (this->copy) = new node*();//Step 2 create an object to hold the node.
     
        (*this->copy)->pass(temp);//Step 3 pass the node from the int main into the new object. 



This part doesn't create an object?

(this->copy) = new node*();

lostwithcpp wrote:
This part doesn't create an object?

(this->copy) = new node*();
It creates a pointer (which is technically an object), but it does not create an instance of your node class.

Why are you using pointer-to-pointer at all?
Last edited on
Topic archived. No new replies allowed.