C++ Access private member of nested class -


the title might bit misleading. have following problem: have tree consisting of leaves , internal nodes. user should able store information in leaves and tree has methods set of user-defined values , need access corresponding leaves in constant time (not amortized).

i came following idea not work because unfortunately cannot access private members of nested class: user creates tree and each leaf instance of userelement contains user_defined value corresponding leaf. once method dosomethingwiththetree(list>) called , tree built, tree creates corresponding leaves , saves in private field leaf. whenever user wants call method of leaves corresponding user_defined values, he/she has call method giving corresponding userelements , tree can retrieve corresponding leaves in constant time.

class tree {     public:         template <typename t>         class userelement {             private:                 t user_value;                 tree_node* leaf; // has private                                  // outside class `tree`             public:                 t getinf() {                     return user_value;                 }                 void setinf(t i) {                     user_value = i;                 }         };          void dosomethingwiththetree(list<userelement<t>> elements) {             ...             // want able access elem.leaf elements         } } 

technically, that's nested class (declared within class), not subclass (which inherits superclass).

you can allow tree class access privates making friend:

class userelement {     friend class tree;     // ... }; 

or, better encapsulation, restrict access member function(s) need it, although gets bit messy due need declare things in right order:

class tree { public:     // declare can declare function     template <typename t> class userelement;      // declare before defining `userelement` can use     // in friend declaration     template <typename t>     void dosomethingwiththetree(list<userelement<t>> elements) {         elements.front().leaf;     }      template <typename t>     class userelement {         // finally, can declare friend.         friend void tree::dosomethingwiththetree<t>(list<userelement<t>>);         // ...     }; }; 

Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -