Sign in to follow this  
Thirthe

[C++] readonly class members?

Recommended Posts

why can't one simply do this and expects for it to work:
class Node{

  int data;
  Node *next;

  public:
    Node(Node *node_new){ data= node_new->data; next= NULL; };
    ~Node(){};

    void setNext(Node *node_new){ next= node_new; };

    int getData(){ return data; };
    int *getNext(){ return next; };

};
see the last 2 members: how can i make them read-only? note that int getData() const { return data; }; int *getNext() const { return next; }; does not work.

Share this post


Link to post
Share on other sites
Quote:
Original post by Thirthe
why can't one simply do this and expects for it to work:
*** Source Snippet Removed ***

see the last 2 members: how can i make them read-only?
note that
int getData() const { return data; };
int *getNext() const { return next; };
does not work.


const int getData() { return data; };
const int *getNext() { return next; };

will make them return a "read-only" int and a pointer to a "read-only" int, respectively. That doesn't make the member functions themselves read-only. Member functions are already read-only.

Share this post


Link to post
Share on other sites
The following Works HereTM:

    int getData() const { return data; }
Node *getNext() const { return next; }


Please define what you mean by read-only (since, by definition, functions returning non-references are read-only members) and what you mean by not working.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this