Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing a member pointer error: cannot be used as member pointer

I've got the following (truncated) class declaration:

template <typename T>
class btree 
{
    public:

        btree(const btree<T>& original); //This is btree's copy constructor

    private:

        struct btree_node 
        {
            btree_node(const btree_node &other)
            {
                //This is node's copy constructor
            }
        }

        btree_node* headNode;
}

And btree's copy constructor is implemented this way:

template <typename T> 
btree<T>::btree(const btree<T>& original)
{
    headNode = new btree_node(original.*headNode);
}

original.*headNode is supposed to return btree_node that original.headNode is pointing to, thus matching btree_node's copy constructor arguments.

However I get the following error:

error: '((btree*)this)->btree::headNode' cannot be used as a member pointer, since it is of type 'btree::btree_node*'

What am I doing wrong?

like image 650
Arvin Avatar asked Apr 30 '26 09:04

Arvin


2 Answers

If you look at the precedence table you will see that first the . operator is evaluated and then the * (dereference) operator is evaluated.

* takes a pointer as argument. If you write original.*headNode, it's meaningless. Somehow you are telling it to get the member *headNode of original, but *headNode is not a member of original. You are also telling it to evaluate *headNode which is actually *this->headNode (note that -> is evaluated first).

What you want is to first get the pointer by writing original.headNode, then dereference it by using *. Therefore

*original.headNode
like image 146
Shahbaz Avatar answered May 03 '26 00:05

Shahbaz


Try this:

headNode = new btree_node(*(original.headNode))
like image 44
Patrik Avatar answered May 03 '26 01:05

Patrik