Why I cant access this private variable?

205 views Asked by At

Im trying to made BST with OOP and my lecturer want me to made the node into class so I made this code

node.h

#ifndef node_h
#define node_h
#include <string>

using namespace std;

class Node{
    public : 
        Node();
        Node(Node* left_node, Node* right_node, string newname, string newaddress, int age);
        ~Node();
        // Getter
        Node* GetLeft();
        Node* GetRight();
        string GetName();
        string GetAddress();
        int GetAge();
        // Setter
        void SetName(string newname);
        void SetAddress(string newaddress);
        void SetAge(int newage);
        void SetLeft(Node* newnode);
        void SetRight(Node* newnode);
    private :
        string name,address;
        int age;
        Node* left;
        Node* right;
};

#endif

node.cpp

#include "node.h"

using namespace std;

Node::Node(){
    Node::name="";
    Node::address="";
    Node::age=0;
    Node::left=NULL;
    Node::right=NULL;
};

Node::Node(Node* left_node, Node* right_node, string newname, string newaddress, int newage){
    Node::left = left_node;
    Node::right = right_node;
    Node::name = newname;
    Node::address = newaddress;
    Node::age = newage;
};

Node::~Node(){

}

// Getter
Node* Node::GetLeft(){
    return left;
};

Node* Node::GetRight(){
    return right;
};

string Node::GetName(){
    return name;
};

string Node::GetAddress(){
    return address;
};

int Node::GetAge(){
    return age;
};

// Setter
void Node::SetName(string newname){
    Node::name = newname;
};

void Node::SetAddress(string newaddress){
    Node::address = newaddress;
};

void Node::SetAge(int newage){
    Node::age = newage;
};

void SetLeft(Node* newnode){
    Node::left = newnode;
};

void SetRight(Node* newnode){
    Node::right = newnode;
};

but when I run it i got invalid use of non-static data member

Anyone can help what should I do so I can set left node and right node? NB : Im not so good with OOP, just start to studying about it, sorry for the bad english too

3

There are 3 answers

2
M.M On BEST ANSWER

The problem is in:

void SetLeft(Node* newnode){
    Node::left = newnode;
};

This SetLeft is not a member of Node, so it cannot access private members of a Node.

You probably meant:

void Node::SetLeft(Node* newnode){

etc. The SetRight just below has the same problem too.

3
João Vitor Cabral On

Instead of:

Node::left = newnode;

use:

this->left = newnode;

By using Node::left you're trying to access a static member, which is not declared.

'this' reflects to the class instance you're working with!

0
PakCoder On

Write SetLeft with scope resolution operator in node.cpp. It is supposed to be written as : void Node::SetLeft(parameters) and SetRight is also supposed to be written in the same way.