2

Suppose I have a base abstract class:

class Foo {
public:
    struct FooStruct;
    virtual FooStruct *DoFoo() = 0;
};

And now I would like to implement the DoFoo in Bar and also define the FooStruct inside it:

class Bar: public Foo {
public:
    struct FooStruct {
        int data;
    };
    FooStruct *DoFoo() {
        FooStruct *fs = new FooStruct;
        fs->data = 42;
        return fs;
    }
};

However, g++ (in my case) recognizes Foo::FooStruct and Bar::FooStruct as two different structures and will complain about invalid covariant type ... because I redefine return type of a method.

How can I fix this?

RostakaGmfun
  • 487
  • 6
  • 21

3 Answers3

1

I guess your pupose is then to do something as:

Foo * my_foo = new Bar();
FooStruct * my_result = my_foo->DoFoo();

The problem is that to use my_result now, you must know that it is implicitely a struct that has been created by Bar. Hence, you should define your returned struct externaly to Foo

xiawi
  • 1,772
  • 4
  • 19
  • 21
0

You can not do what you are seemingly trying to do. Virtual functions should have the same static return type everywhere across the hierarchy, and Foo::FooStruct has nothing to do with Bar::FooStruct. What you seem to be craving is something like following:

// In Foo.h
struct FooStruct { virtual ~FooStruct() = default; }

class Foo {
public:
    virtual FooStruct* DoFoo() = 0;
    virtual ~Foo() = default;
};

// In Bar.h
struct DerivedFooStruct : FooStruct { };
struct Bar : public Foo {
    FooStruct* DoFoo() { return new DerivedFooStruct(); } // Never mind memory mgmt
};
SergeyA
  • 61,605
  • 5
  • 78
  • 137
0

You're trying to create a monster that doesn't fit into the C++ type system.

Imagine someone is trying to use a Foo pointer polymorphically:

Foo* ptr = .... ; //getting the value from somewhere, e.g. an API call
??? result = ptr->DoFoo();

What's going to be the type of the return value? The compiler doesn't know it.

Use a common base class for the struct you're going to return. A forward declaration won't cut it.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176