0

I want to have different implementation hidden behind a unique interface.
I tried the answers to this question, but it seems that the only thing that it does is to force developers to implement certain methods.

Using the answer to the question mentioned, this is what I'd like to do.

#include <iostream>
using namespace std;

class Interface
{
    public:
        virtual ~Interface() {}
        virtual void OverrideMe() = 0;
};

class Implementation1 : public Interface
{
    public:
        virtual void OverrideMe()
        {
            cout << "1" << endl;
        }
};

class Implementation2 : public Interface
{
    public:
        virtual void OverrideMe()
        {
            cout << "2" << endl;
        }
};

int main(int argc, char *argv[])
{
    Interface a = Implementation1();
    Interface b = Implementation2();

    a.OverrideMe(); //expecting 1
    b.OverrideMe(); //expecting 2
}

This does not compile, and I could find a way to have a type that allows different behavior based on the constructor.
Even if I add the Parent class mentioned in the answer, the program does not compile.

lblenner
  • 372
  • 2
  • 14
  • 4
    You should work with **pointers** to base class. That is, ```Interface *a = new Implementation1();```. Read more about runtime polymorphism first. – Yurii A Apr 06 '21 at 13:42
  • 8
    See [what is object slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing). If you want polymorphism of this type you'll need to use some kind of pointers or references, preferably smart ones that manage lifetimes. – Nathan Pierson Apr 06 '21 at 13:43
  • 2
    "_This does not compile_" Why not? Post the full error. – underscore_d Apr 06 '21 at 13:44
  • I don't think the error is important as this is only one of the attempt to implement the desired behavior. – lblenner Apr 06 '21 at 13:47
  • 3
    This is one of the cases where the compile error is your friend. – Caleth Apr 06 '21 at 14:05

0 Answers0