Arvin
Arvin

Reputation: 1431

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?

Upvotes: 2

Views: 5334

Answers (3)

Shahbaz
Shahbaz

Reputation: 47533

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

Upvotes: 6

K-ballo
K-ballo

Reputation: 81349

I assume what you want is actually

headNode = new btree_node( *original.headNode );

Upvotes: 3

Patrik
Patrik

Reputation: 2692

Try this:

headNode = new btree_node(*(original.headNode))

Upvotes: 6

Related Questions