samedi 27 juillet 2019

Accessing outer class from inner class without explicitly passing an instance

The following code produces the output

outer::inner::inner, o=00000000
outer
outer::inner::val, o=00000000
outer::print

Can anyone explain how I can access the outer class method print through o without explicitly assigning o's value at construction?

#include <iostream>

class outer {
public:
    outer() { 
        std::cout << __func__ << std::endl; 
    }

    class inner {
        outer *o = nullptr;
    public:
        inner() { 
            std::cout << __FUNCTION__ << ", o=" << o << std::endl;
        }
        void val() { 
            std::cout << __FUNCTION__ << ", o=" << o << std::endl;
            o->print(); // **call outer class method**
        }
    };

    inner i;

    void print() { 
        std::cout << __FUNCTION__ << std::endl;
    }
};

int main()
{
    outer o;
    o.i.val();

    return 0;
}

This way, I can do something like

template <typename T>
class example {
    outer *c = nullptr;
public:
    void fn() {
        c->print();
    }
};

if I have

class outer {
    // other code
public:
    example<int> ie;
    // other code
};

Aucun commentaire:

Enregistrer un commentaire