-1

I want to use a abstract class as Interface in C++ for reasons :) like this:

    class Base{
    public:
        virtual bool foo() = 0;
        int getValue() {return this->value;};

        int compare(Base other) {
            //calculate fancy stuff using Base::foo() and other given stuff through inheritance
            return result;
        }

    protected:
        int value;
    };

    class TrueChild: public Base{
    public:
        TrueChild(int value): Base() { this->value = value;}
        bool foo() {return 1;}
        //do stuff with value
    };

    class FalseChild: public Base{
    public:
        FalseChild(int value): Base() { this->value = value;}    
        bool foo() {return false;}
        //do other stuff with value
    };

But I can't pass Base as type in the compare method because it's a abstract class and I can't instantiate it. C++ complains with cannot declare parameter ‘first’ to be of abstract type ‘Base’ . How can I create a method that takes params with type of any class, which implements the Base class?

I know it is kind of similar to questions like this, this or this, but these answers don't help, because they doesn't talk how to use the Interface as generalized type in any way.

Thank you :)

Community
  • 1
  • 1
KuSpa
  • 325
  • 4
  • 14
  • Don't use Java as a model in writing C++ code. Any good C++ book would have explicitly have the `Base` parameter as a reference or pointer, not an object. – PaulMcKenzie Mar 16 '17 at 22:04
  • 1
    I don't know where `first` is but you are passing an object instead of a reference or pointer to an object. – jiveturkey Mar 16 '17 at 22:04
  • okay, if i use a reference It works. what do I return if I want to return the "bigger" object for example? do i have to use ```template ``` then? – KuSpa Mar 16 '17 at 22:16
  • First understand that C++, something exists that doesn't exist in Java -- *object slicing*. You cannot return or pass a base class, and in the caller, have the full object available. The reason is that the derived portion of that object has been "sliced off" -- you're trying to stuff 10 pounds of potatoes in a 5 pound bag.. You return a `Base` object, you're going to get a `Base` object -- you pass a `Base`,object you're passing a `Base` object. You can't cast to a derived object as you would in Java from a Base object. – PaulMcKenzie Mar 17 '17 at 00:33
  • is there any workaround? – KuSpa Mar 17 '17 at 10:05

1 Answers1

1

How about

int compare(Base const& other);

Which you would then use as:

trueChild.compare(falseChild);
ssell
  • 6,429
  • 2
  • 34
  • 49