Kuba Spatny
Kuba Spatny

Reputation: 26978

Initializing const pointer - initializer list in c++

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?

Upvotes: 0

Views: 1315

Answers (1)

juanchopanza
juanchopanza

Reputation: 227418

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.

Upvotes: 6

Related Questions