Accessing data from a nested friend class

Hello forum,
I have a question on how to access data from an enclosing class. I have a code similar to,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class foo
{
  friend class bar;

  public:
    // . . .

  private:
    int attribute_0 = 100;
    std::string attribute_1 = "foo";

  class bar
  {
    public:
      void PrintBooBar()
      {
        //here is the problem. how access attribute_0 from foo??
        std::cout << foo::attribute_0 << attribute_0 << std::endl;
      }
 
    private:
      int attribute_0 = 200;
      std::string attribute_1 = "bar";
  } attribute_2;
}


Accessing attribute_0 in foo via foo::attribute_0 doesn't seem to work. I know I can get around this by passing the this pointer to the nested class, but I'm looking for something nicer...seems like it should be possible. I'd definitely appreciate any pointers on this. Thanks

Edit: This is for c++11 with VS 2013 compiler. My understanding is that in c++11 nested classes should have access to enclosing private members?
Last edited on
Not possible unless attribute_0 in foo is static or you pass in a pointer to a foo object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Example program
#include <iostream>
#include <string>

class foo {
  friend class bar;
  
  public:
    void action() { attribute_2.PrintFooBar(this);}
    
  private:
    int attribute_0 = 100;
    std::string attribute_1 = "foo";

  class bar {
    public:
      void PrintFooBar(foo* f) {
        //here is the problem. how access attribute_0 from foo??
        std::cout << f->attribute_0 << " " <<  attribute_0 << std::endl;
      }
 
    private:
      int attribute_0 = 200;
      std::string attribute_1 = "bar";
  } attribute_2;
} f;

int main() {
    f.action();
    return 0;
}


You can do this in Java by using the syntax ClassName.this.attribute

See this other answer:
https://stackoverflow.com/questions/11405069/inner-class-accessing-outer-class
Last edited on
ahh ok. oh well, would have been nice.
Topic archived. No new replies allowed.