Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overload subscript operator does not return pointer

In my class, I have a member variable std::vector<node*> children
I want to overload the subscript operator so that I can easily index one of the nodes.


Here is my class deceleration for that function:

node* operator[](int index);  

Here is my class definition for that function:

node* class_name::operator[](int index){

    return children[index];
}  

However, this function does not seem to return a pointer as I had hoped.
Here is the function that is giving me trouble:

void Print_Tree(node* nptr, unsigned int & depth){

    if (NULL == nptr) {
        return;
    }
      //node display code

    for (int i = 0; i < nptr->Number_Of_Children(); ++i){
        Print_Tree(nptr[i],depth+1); //<- Problem Here!
    }
     //node display code

    return;
}  

The error I get is:

error: cannot convert ‘node’ to ‘node*’ on the recursive call

I don't understand why it gives me back a node when I want a pointer to a node.
Is there something wrong with my overloaded function?
I tried dereferencing the node in the recursive call:

Print_Tree(*nptr[i],depth+1);  
Print_Tree(*(nptr[i]),depth+1);
Print_Tree(nptr->[i],depth+1);

to no avail!

What am I doing wrong?

like image 679
Trevor Hickey Avatar asked Sep 16 '12 07:09

Trevor Hickey


2 Answers

Your are looking for the problem in the right place, but the syntax in your three correction attempts is still slightly wrong.

nptr is a pointer to a Node object, so you cannot apply the index operator directly (if you do, the compiler will assume it points to the beginning of a Node array and jump to the ith entry).

Instead you need to first dereference the pointer, and then apply the index operator. Use parentheses to determine the order of this:

Print_Tree((*nptr)[i],depth+1);

On a separate note, your using int as the data type for the index into the vector is slightly incorrect. Better use std::size_t or std::vector<Node*>::size_type.


Furthermore, given that this question is tagged c++11, I should point out that the correct way to refer to the null pointer is nullptr, not NULL.

like image 72
jogojapan Avatar answered Sep 22 '22 02:09

jogojapan


Even though it is indeed legal to have operator[] return a pointer, it is better design (and fits expectations from standard classes) to return a reference instead. You can then take the address of that reference as follows:

node& class_name::operator[](int index){
    return *(children[index]);
}

and then use it as:

Print_Tree(&(*nptr)[i],depth+1);
like image 36
epsalon Avatar answered Sep 19 '22 02:09

epsalon