user6490375
user6490375

Reputation:

Creating an object of an interface in C++

I know this question is a bit odd, but please bear with me.

I am designing an OOD for a parking lot. I want to allow only those vehicles to park, that have an autopark feature in them. In Java, I would have created an interface and only the objects of that interface (i.e., the cars with autopark features) would have been allowed to park. In C++, interfaces are created using abstract classes with pure virtual methods. So, I cannot create objects of this 'C++ interface'. So, how do I achieve this in C++?

Note: I know of other techniques like using some flag to denote the presence or absence of autopark feature, etc; but I am not interested in those workarounds.

Upvotes: 4

Views: 2995

Answers (1)

You're looking for a way to create anonymous concrete classes.

In C++, you can create anonymous structures by treating the structure/class as the 'type' for a variable declaration. Below, we have the implementing class (note that it's anonymous but still extends Foo, our pure-virtual/'abstract' base class) and instead of ending with the semicolon, we give it a variable name to immediately allocate an instance of that anonymous class on the stack.

Consequently, this is why classes, structs and enumerations in both C and C++ must end with a semicolon (whereas things like namespace do not).

#include <iostream>

using namespace std;

class Foo {
public:
    virtual void bar() = 0;
};

void callBar(Foo *foo) {
    foo->bar();
}

int main() {
    class : public Foo {
        virtual void bar() {
            cout << "Hello from foo1" << endl;
        }
    } foo1; // <-- Note that we immediately create foo1 here...

    class : public Foo {
        virtual void bar() {
            cout << "Bonjour from foo2" << endl;
        }
    } foo2; // <-- ... and foo2 here.

    callBar(&foo1);
    callBar(&foo2);

    return 0;
};

Upvotes: 3

Related Questions