-3

I have defined a struct within a class as follows:

class my_header {

public:
    my_header();

    struct add_x {
        double operator()() const { return a; }
    } add_x;

private:
    double a{1.0}; 
};

When compiling (g++ -std=c++11), I got the following errors:

./my_header.h:19:40: error: use of non-static data member 'a' of
      'my_header' from nested type 'add_x'
                double operator()() const { return a; }

Is it possible to access private members of the class from the struct defined within the class itself?

RangerBob
  • 473
  • 3
  • 13
  • 2
    `add_x` is a distinct type that doesn't inherit or otherwise have access to an instance of `my_header`. – François Andrieux Jul 11 '18 at 20:53
  • Why are you declaring this additional `struct` layer? That's not a member function, it has no access to any particular `my_header` instance. It only has access to `add_x`. – tadman Jul 11 '18 at 20:53
  • 1
    `a` is not `static`, so `add_x` needs a pointer/reference to a `my_header` instance in order to access its `a` member. As for the `private` issue, prior to C++11, you would have to explicitly declare `add_x` as a `friend` of `my_header`. In C++11 and later, [`add_x` has access to `my_header`'s members](https://stackoverflow.com/questions/5013717/). – Remy Lebeau Jul 11 '18 at 20:55
  • 4
    Perhaps you are confusing how c++ nested classes work with how java nested classes work. Java nested classes are always associated with an instance of the outer class. This isn't the case in c++, nested classes can exist independently from any instance of the outer class. – François Andrieux Jul 11 '18 at 20:55
  • @FrançoisAndrieux "*Java nested classes are always associated with **an instance of** the outer class*" - thanks for that! I always wondered how use of `outer.this` inside an `inner` class worked, that always confused me. Now I finally get it. I was missing the link that an inner class object instance is actually part of an outer class object instance, not a separate object. – Remy Lebeau Jul 11 '18 at 21:02
  • @tadman could you please take a look at this problem please https://ibb.co/niqDnT – Vinay Shukla Jul 11 '18 at 21:15
  • 1
    That image describes something completely different than what you're doing here. Can you explain the connection? – tadman Jul 11 '18 at 21:34
  • I did not show any picture! What are you talking about? – RangerBob Jul 11 '18 at 21:51

1 Answers1

0

The problem is that the add_x instance of the add_x nested type does not know the correct instance of my_header to use for accessing the field my_header::a. Which is why it complains about a being non-static (if it were static, it would know what a you were asking for).

An alternative would be to have add_x take a reference to my_header in its constructor, and use that instance to access a.

Michael Price
  • 8,088
  • 1
  • 17
  • 24