Boost logo

Boost :

Subject: [boost] outer class `this` in local classes
From: Lorenzo Caminiti (lorcaminiti_at_[hidden])
Date: 2010-06-24 13:06:15

Hello all,

Is there a way to access the outer class `this` from a local class but
without using inheritance?

Let me explain with an example:

    class x { // outer class
        void g() {}

        void f() {
            this->g(); // (1)

            struct y: x { // local class *** using inheritance ***
                y(x* super): x(*super) {} // (2)
                void h() {
                    this->g(); // (3)

*** Is there a way to do this but without inheriting `y` from `x`? ***

At line (3), the local class `y` can access the outer class `x::g()`
simply using `this` because `y` inherits from `x`. However, this
inheritance requires to construct another object `x` when `y` is
constructed as in line (2) adding runtime overhead and requiring `x`
to have an accessible copy constructor.

In my application, I need line (3) to essentially look like line (1)
so you can program code inside `y` members as if it were inside `x`
members. A part from that, the local class `y` could look as it is
needed to solve this problem -- with some member variables, other
member functions, etc. (For example, I tried to redefine
`y::operator->()`/`y::operator*()` to return a pointer/reference to
`x` but this does not work because `this->`/`*this` always retain its
pointer semantics and they do not use the user defined operators...)

Thank you very much.


Boost list run by bdawes at, gregod at, cpdaniel at, john at