Nested Class member function can't access function of enclosing class. Why?
Asked Answered
W

5

26

Please see the example code below:

class A
{
private:
    class B
    {
    public:
        foobar();
    };
public:
    foo();
    bar();
};

Within class A & B implementation:

A::foo()
{
    //do something
}

A::bar()
{
    //some code
    foo();
    //more code
}

A::B::foobar()
{
    //some code
    foo(); //<<compiler doesn't like this
}

The compiler flags the call to foo() within the method foobar(). Earlier, I had foo() as private member function of class A but changed to public assuming that B's function can't see it. Of course, it didn't help. I am trying to re-use the functionality provided by A's method. Why doesn't the compiler allow this function call? As I see it, they are part of same enclosing class (A). I thought the accessibility issue for nested class meebers for enclosing class in C++ standards was resolved.

How can I achieve what I am trying to do without re-writing the same method (foo()) for B, which keeping B nested within A?

I am using VC++ compiler ver-9 (Visual Studio 2008). Thank you for your help.

Walterwalters answered 17/6, 2010 at 1:7 Comment(0)
D
32

foo() is a non-static member function of A and you are trying to call it without an instance.
The nested class B is a seperate class that only has some access privileges and doesn't have any special knowledge about existing instances of A.

If B needs access to an A you have to give it a reference to it, e.g.:

class A {
    class B {
        A& parent_;
    public:
        B(A& parent) : parent_(parent) {}
        void foobar() { parent_.foo(); }
    };
    B b_;
public:
    A() : b_(*this) {}
};
Discotheque answered 17/6, 2010 at 1:33 Comment(7)
+1, just a nitpick - parent is probably not the best name for member variable here - easy confusion with inheritance.Koine
I just wanted to mention that there had be a very good design reason for the nested class B to have a reference to class A.Ylem
Thank you for the explanation with example. The C++ standard 11.8, which I was guessing that it had changed, talks about the class member access by nested class. I know that gcc allows the access by nested class (I'm sure about it) but MS VC compiler doesn't. Hmm... interesting.Walterwalters
@Rahul: Yes, you have access privileges, but there is no implicit relationship between instances - its only a class of which you still have to create instances explicitly.Discotheque
@Nikolai: Hm, i find it clear as it makes the ownership-relation explicit and parents in a inheritance context are often labelled base. At least i can't imagine a better name in a generic example - any suggestions?Discotheque
@Georg, I usually call these like outer or enclosing or something, but that's just my taste. As I said - a nitpick.Koine
Embarcadero C++Builder compiler won't permit the inner class to access containing class methods if they are private or protected. It emits E2247 <method name> is not accessible. If I change to public, it works. I have a similar situation but I don't want to expose the containing class methods to the public.Riggle
D
2

This is an automagic, albeit possibly nonportable trick (worked on VC++ since 6.0 though). Class B has to be a member of class A for this to work.

#ifndef OUTERCLASS
#define OUTERCLASS(className, memberName) \
    reinterpret_cast<className*>(reinterpret_cast<unsigned char*>(this) - offsetof(className, memberName))
#endif 

class A
{
private:
    class B
    {
    public:
        void foobar() {
           A* pA = OUTERCLASS(A, m_classB);
           pA->foo();
        }
    } m_classB;
public:
    foo();
    bar();
};
Duodenary answered 17/6, 2010 at 1:42 Comment(2)
Thank you, Igor for respnding to my question and providing an example. You and Georg have almost similar implementation with a reference back to the outer class, however, I have selected Georg's response as it is cleaner.Walterwalters
No worries, this is after all a pretty nasty looking hack. Having said that, it's been pretty reliable and it's kinda fun :)Duodenary
I
1

Basically what Georg Fritzsche said

#include <iostream>
#include <cstring>
using namespace std;

class A
{
private:
    class B
    {
     A& parent_;
     public:
        //B();  //uncommenting gives error
        ~B();
        B(A& parent) : parent_(parent) {}

        void foobar() 
        { 
         parent_.foo();  
         cout << "A::B::foo()" <<endl; 
        }

        const std::string& foobarstring(const std::string& test) const 
        { 
         parent_.foostring(test); cout << "A::B::foostring()" <<endl;
        }
    };
public:
    void foo();
    void bar();
    const std::string& foostring(const std::string& test) const;
    A(); 
    ~A(){};
    B b_;
};

//A::B::B() {}; //uncommenting gives error
A::B::~B(){};

A::A():b_(*this) {}


void A::foo()
{
    cout << "A::foo()" <<endl;
}

const std::string& A::foostring(const std::string& test) const
{
    cout << test <<endl;
    return test;
}

void A::bar()
{
    //some code
    cout << "A::bar()" <<endl;
    foo();
    //more code
}

int main(int argc, char* argv[])
{
A a;
a.b_.foobar();
a.b_.foobarstring("hello");

return 0;
}

If you uncomment the default B constructor you would get an error

Icono answered 15/5, 2012 at 19:22 Comment(2)
@cbinder try uncommenting A::B::B() {}; tooIcono
If you want to use B() class constructor, then you can use reinterpret_cast for this. You can refer this: https://mcmap.net/q/520027/-nested-class-member-function-can-39-t-access-function-of-enclosing-class-whyCristencristi
U
0

If you want to reuse functionality from A then you should inherit from A not nest B inside it.

Univalent answered 17/6, 2010 at 1:16 Comment(1)
I am not extending the fucntionality of A in B, so, there's no need for inheriting B from A. Also, I would like to keep B hidden from the users of class A.Walterwalters
C
0

Combining Igor Zevaka's and enthusiasticgeek's answers. Also, using reinterpret_cast for calculating offset (If you create class member variable using new keyword):

#include <iostream>
#include <cstring>
using namespace std;

template < typename T, typename U > constexpr size_t offsetOf(U T:: *member)
{
    return (char*) &((T*) nullptr->*member) - (char*) nullptr;
}

class A
{
    private:
        class B
        {
         public:
            B(string message);
            ~B();

            void foobar()
            {
                A *pA = reinterpret_cast<A*> (reinterpret_cast< unsigned char*> (this) - offsetOf(&A::b_));
                pA->foo();
                pA->bar();
                std::cout << "DONE!";
            }
        };
    public:
        void foo();
        void bar();
        A();
        ~A() {};
        B* b_ = new B("Hello World!");
};

A::A() 
{
    cout << "A constructor\n";
};
A::B::B(string message) {
    cout << "B constructor\n";
    cout << "Message =  " << message << "\n";
};
A::B::~B() {};

void A::foo()
{
    cout << "A::foo()" << endl;
}

void A::bar()
{
    cout << "A::bar()" << endl;
    foo();
}

int main(int argc, char *argv[])
{
    A* a = new A();
    a->b_->foobar();

    return 0;
}

Output:

B constructor
Message =  Hello World!
A constructor
A::foo()
A::bar()
A::foo()
DONE!

References:

https://mcmap.net/q/520027/-nested-class-member-function-can-39-t-access-function-of-enclosing-class-why

https://mcmap.net/q/520027/-nested-class-member-function-can-39-t-access-function-of-enclosing-class-why

https://mcmap.net/q/520924/-how-to-calculate-offset-of-a-class-member-at-compile-time

Cristencristi answered 24/6, 2021 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.