C ++ covariant error with multiple inheritance

I have code that is equivalent to this:

class X {};
class Y {};

template< typename T>
  class C {
  public:
      virtual  T * foo() = 0;
  };

class A : public C< X> {
public:
    X * foo() {};
};

class B : public A {};

class D : public B, public C< Y> {
public:
    Y * foo() {}; //this is the only one method I need here. Not A::foo!
};

I got the following errors:

error:   invalid covariant return type for 'virtual Y* D::foo()'
 Y * foo() {};
     ^

and

error:   overriding 'virtual X* A::foo()'
 X * foo() {};
     ^

http://ideone.com/PAgTdX

I believe that I can write something in classes B or D to prevent the inheritance of A :: foo, but I don't know what. Perhaps there is some function to rename conflict names in C ++?

PS> I can not use C ++ 11, only the good old C ++ 98.

+4
source share
3 answers

TL DR

foo D. foo - X Y. - , .


:

class X {};
class Y {};

template<typename T>
class C {
public:
    virtual T * foo() = 0;
};

class A : public C<X> {
public:
    // Your code:
    // X * foo() {}; <---- This method is irrelevant to the problem

    // virtual X * foo() {};
    // ^^^^^^^^^^^^^^^^^^^^^
    // This method declared via inheritance and template
    // and implicitly exists in this class, (look at keyword `virtual`)
};

class D : public A, public C<Y> {
public:
    /*virtual*/ Y * foo() {}; // `virtual` comes from C<X>
};

, D foo A C<Y>. , , , D d; d.A::foo();.

 

, foo D:

/*virtual*/ Y * foo() {};

D X * foo(), A, Y * foo(). , , Y X. , foo , .

 

clang:

error: 'foo' , ( "Y *" "X * ')

virtual Y * foo() {};

- , !

+1

, foo, C<X> A, D -an A a C<X>, X. ++ AFAIK, , .

C<X>::foo , D , A, B C<X>. , . A B D, , , .

0

You can use personal inheritance for A.

class B : private A {};

In the general case, the type of return cannot be the only difference when overloaded.

-1
source

All Articles