0

I built an iterator class for my container that looks like this

template <typename T> 
class binary_tree_iterator {
private:
    binary_tree<T>* tree;
public:
    ...
    bool operator!=(const binary_tree_iterator& rhs) const {return tree->data() != rhs.tree->data();}
};                            
                                                      This thing ----------------------^

My best understanding is that I'm passing an instance of my class into another instance of my then class and then accessing a private data member of one within the other. Is this allowed because they are instances of the same class or am I missing something?

Data() just returns data from container.

Joemoor94
  • 173
  • 8
  • I also need to return a reference for my dereference operator. Do I need to store a copy of this data()'s return value in order to reference it? – Joemoor94 Feb 04 '21 at 02:10
  • Aren't you just looking for `friend`? Besides you're not showing a [example]. – user202729 Feb 04 '21 at 02:10
  • And [edit] the question to include more info. – user202729 Feb 04 '21 at 02:10
  • @user202729 I'm not sure what to add. My code works as is and I'm wondering why. The operator works just fine. – Joemoor94 Feb 04 '21 at 02:14
  • Okay, it works, but you should include a [example] in the question (currently there's no `binary_tree` definition in the code) and explain why you think it should raise an error. – user202729 Feb 04 '21 at 02:16
  • 2
    Any instance of a class can operate on the `privete` members of any other instance of the same class it can get its hands on. `binary_tree_iterator` can see the insides of every `binary_tree_iterator` – user4581301 Feb 04 '21 at 02:16
  • @user202729 I mean, I guess I could shorten the variable names – Joemoor94 Feb 04 '21 at 02:17
  • No, not that (the variable names are descriptive and looks fine), but you didn't include the definition/declaration of `binary_tree`. Something like `class binary_tree{ int data(); };` would make the code compile. – user202729 Feb 04 '21 at 02:19
  • Anyway, your question is answered anyway (it's clear enough without a [example] -- but make sure to make the example complete before asking. – user202729 Feb 04 '21 at 02:20
  • @user202729 Yes, thank you – Joemoor94 Feb 04 '21 at 02:22

1 Answers1

1

Private methods / fields aren't private to an instance of the object -- they're private to the class itself. So you can pass a Foo into another Foo instance and access everything.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36