0

I am currently trying to implement tree structure in C++. I started with following code:

class Tree {
    Node * const first;
    Node * last;
public:

    Tree(Node * const root)             
        {
            first = root;
            last = first;
        };
}

But of course it gave me these errors:

error: uninitialized member ‘Tree::first’ with ‘const’ type ‘Node* const’ [-fpermissive]

error: assignment of read-only member ‘Tree::first’

I looked into the problem and found out that I have to use initializer list. I tried, but it didn't go very well.

Tree(Node * const root)
:first()              
{
    first->id = 0;
    first->sibling = first;
    first->point = root->point;
    last = first;
};

With this, the problem ends with "Run failed", no errors, no exceptions.

So I even tried just:

Tree(Node * const root)
:first()              
{
};

But the Node constructor isn't even called..

So what am I doing wrong?

1 Answer 1

6

You are not initializing your const pointer, but assigning to it. As it is const, you cannot do that. You must initialize it in the constructor initialization list:

Tree(Node * const root) : first(root)
{
  ....
}

Remember, once you get to the constructor's body, all data members have been initialized, be it implicitly or explicitly.

Sign up to request clarification or add additional context in comments.

2 Comments

Okay this is the correct answer. However I am even more lost now, could you, please, explain (or just point me to a source) what actually happens in "first(root)"?
@KubaSpatny what happens is that first is initialized to hold the value of root, i.e. it points to whatever root points to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.