0

I've got a class where one of the private properties is an instance of the class. In Java (because I'm used to Java) this looks like:

class Node {
    private Node Pi;
}

And now I'm writing this in C++, and when I try to do the same thing, I get a red underline (I'm using Visual C++ 2010 Express), "Incomplete type is not allowed".

class Node {
    private:
        Node Pi; //Incomplete type is not allowed
};

I've tried fixing this by changing it to Node Pi(void); but then why I try to use another function that modifies this property I get "Expression must be a modifiable lvalue".

class Node {
    private:
        Node Pi(void);
    public:
        void setPi(Node n);
};
void Node::setPi(Node n) {
    Pi = n; //Node Node::Pi() expression must be a modifiable lvalue
}

Normally in Java there's no problem with this, so my question is, how do I implement this? I'm not a beginner to C++, but I haven't written with it for a while.

class Node {
    private Node Pi;
    void setPi(Node n) {
        this.Pi = n;
    }
}
Polyov
  • 2,281
  • 2
  • 26
  • 36
  • "Incomplete type not allowed" means you can't create an instance of a class that hasn't been fully-defined yet. A class isn't "complete" until the compiler reads its closing brace and semicolon. A class can't contain an instance of itself; that'd be a circular definition. – Wyzard Nov 07 '12 at 01:35

4 Answers4

4

Turn Pi into a reference or a pointer to Node.

  1. A reference (Node& Pi) will result in nicer syntax, but can't be null, will have to be initialized at construction and cannot be changed to refer to a different object.
  2. A pointer (Node* Pi) will require less pretty syntax, but can be null and can be made to point to different objects at different times.

For more details, see What are the differences between a pointer variable and a reference variable in C++?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Try this: (Send pointer to objects instead of class objects directly)

class Node {
    private:
        Node* Pi(void);
    public:
        void setPi(Node* n);
};

void Node::setPi(Node* n) {
    Pi = n; //Node Node::Pi() expression must be a modifiable lvalue
}

Java 'auto-magically' converts those objects, with C++, you have to do it yourself.

Vaibhav Desai
  • 2,618
  • 1
  • 16
  • 16
1

Java's syntax hides the fact that it uses pointers everywhere. In C++ you have to use pointer syntax explicitly in order to mimic Java:

// Java
class Node {
    private Node Pi; // This is actually a pointer
}

// C++
class Node {
    private:
        Node *Pi; // So you use a pointer in C++ too
};
bames53
  • 86,085
  • 15
  • 179
  • 244
0

Change the following code :

class Node {
    private:
        Node Pi; //Incomplete type is not allowed
};

To:

class Node {
    private:
        Node* Pi; 
};