NebulaFox
NebulaFox

Reputation: 8313

C++ Abstract type initialisation

I have a class Interface, that has pure virtual methods. In another class I have a nested type that inherits from Interface and makes it non-abstract. I use Interface as a type and use the function to initialise the type, but I am getting, cannot compile because of abstract type.

Interface:

struct Interface
{
   virtual void something() = 0;
}

Implementation:

class AnotherClass
{
    struct DeriveInterface : public Interface
    {
        void something() {}
    }

    Interface interface() const
    {
        DeriveInterface i;
        return i;
    }
}

Usage:

struct Usage : public AnotherClass
{
    void called()
    {
        Interface i = interface(); //causes error
    }
}

Upvotes: 0

Views: 254

Answers (2)

jpalecek
jpalecek

Reputation: 47762

You use abstract classes as pointer and references, so you'd do

class AnotherClass
{
    struct DeriveInterface : public Interface
    {
        void something() {}
    }

    DeriveInterface m_intf;

    Interface &interface() const
    {
        return m_intf;
    }
}

struct Usage : public AnotherClass
{
    void called()
    {
        Interface &i = interface();
    }
}

plus a couple of semicolons and it will work fine. Note that only pointers and references are polymorphic in C++, so even if Interface were not abstract, the code would be incorrect because of so-called slicing.

struct Base { virtual int f(); }
struct Der: public Base { 
   int f(); // override
};

...
Der d;
Base b=d; // this object will only have B's behaviour, b.f() would not call Der::f

Upvotes: 4

ypnos
ypnos

Reputation: 52327

You need to work with an Interface* here.

Upvotes: 0

Related Questions