c++classc++17member-variables

Cpp Compile "error: unknown type name" when initializing object as member variable of other class


I'm new to C++. I am initializing a class object Node in another class LCache. When I try to compile my code, I get the following error:

Line 22: Char 5: error: unknown type name 'left'
    left -> next = right;
    ^

Below is the code I have written:

class Node{
public:
    int k;
    Node* prev;
    Node* next;
    
    Node (int key){
        k=key;
        prev=NULL;
        next=NULL;
    }
};

class LCache {
private:
    Node* left = new Node(0);
    Node* right = new Node(0);
    left -> next = right;
    right -> prev = left;
...

When I move left -> next = right; and right -> prev = left; inside a method in class LCache, the error goes away. Can you explain the reason here?


Solution

  • You can't perform non-declaration statements inside of a class declaration, like you are trying to do. You need to perform them inside of a class member function instead, or in this case inside of the class constructor (like you did with Node), eg:

    class Node{
    public:
        int k;
        Node* prev;
        Node* next;
        
        Node (int key){
            k = key;
            prev = NULL;
            next = NULL;
        }
    };
    
    class LCache {
    private:
        Node* left = new Node(0);
        Node* right = new Node(0);
    
        LCache() {
            left->next = right;
            right->prev = left;
        }
    
        ~LCache() {
            delete left;
            delete right;
        }
    
        ...
    };
    

    That being said:

    NULL is deprecated in modern C++, use nullptr instead.

    And you should use smart pointers whenever you have owned pointers that need freeing when they are done being used. Or better, just don't use objects dynamically when you don't actually need to.

    Try something more like this instead:

    class Node{
    public:
        int k;
        Node* prev = nullptr;
        Node* next = nullptr;
        
        Node (int key) : k(key) {}
    };
    
    class LCache {
    private:
        std::unique_ptr<Node> left = std::make_unique<Node>(0);
        std::unique_ptr<Node> right = std::make_unique<Node>(0);
    
        LCache() {
            left->next = right;
            right->prev = left;
        }
    
        ...
    };
    
    /* alternatively:
    
    class LCache {
    private:
        Node left{0};
        Node right{0};
    
        LCache() {
            left.next = &right;
            right.prev = &left;
        }
    
        ...
    };
    */