Search code examples
c++instantiationinner-classesouter-classes

Initialize Inner Class with outer class this possible?


Today i tried to instanciate an inner class while passing my outer class to it and while i am in the namespace of the outer class: I'm using Visual Studo 2013. Code looks like this : (watch the ^^)

class Base
{
public:
    virtual void foo(){ cout << "foo" };
};

class object
{
    class Derived : public Base
    {
        object& o;
    public:
        Derived(object& o) : o(o){}
        virtual void foo(){ cout << "bar" };
    }derived(*this);
//          ^^^^^^
};

The derived class inheriting something does not affect anything for this example here as far as i tested. (only in here for context reasons , see below)

On this ^^ point i recieve error: no appropriate default constructor available

Intellisense warns me, that it expects type specification. I also tried passing a pointer (of course i changed construktors then, too)but same reaction. For protokoll i tried quite a lot of variations and research by now, but i cannot isolate a clear answer to my problem.

Is the "this" pointer not usable here ? How can i pass myself then at this point ?

For Background (only if you're interested):

I tried to write Code for Keybinding in an Application. To pass functions to the Keys i use an "Interface" of class KeyFunction (Base class resembles it).

I now want to give classes (object) the possibility to declare it's own KeyFunction(Derived) and , more important, pass ressources(object) with it, in a way that functions can work on them (since i can only use void pointers, because they are later stored in an array for the bindings) I already achieved this task with other code which i think is to long to post here, though. By experimenting i stumbled across this problem.


Solution

  • Your compilation error has nothing to do with your class hierarchy, but with the simple fact that this is not how you go about constructing a class instance.

    Try actually declaring a class member, and a class constructor:

    class Base
    {
    public:
        virtual void foo(){ }
    };
    
    class object
    {
        class Derived : public Base
        {
            object& o;
        public:
            Derived(object& o) : o(o){}
            virtual void foo(){ }
        };
    
        Derived derived;
    
        object() : derived(*this)
        {
        }
    };