Victor Bazarov wrote:
Bit byte wrote:
I have a base (abstract) class with a public method foo delared as:
virtual BaseClass* foo(..)=0;
I wnat to derive two classes A and B from Baseclass so that I return a
pointer for A and B respectively (i.e. A::foo() returns a A*, and
B::foo() returns a B*).
I notice that if I declare the foo in A and B like this:
A* A::foo(...);
B* B::foo(...);
The compiler barfs.
Sounds like you have a rather old compiler that doesn't accept what is
known as "covariant return types".
I am thinking of doing the ff:
1). leave the signature unchanged (ie. BaseClass* A::foo(), BaseClass*
B::foo()
2). Create the appropriate pointer in the method and then return it
as a BaseClass*.
Sounds like a good work-around.
I have two questions:
1). Is this the correct way to do this?
It's a work-around. A more correct way would be to get a better compiler.
2). Can I overload AND overide a function (i.e. can A::foo() take
different arguments?)
Yes. Remember, though, that you cannot _overload_ a function from another
class. You need to bring it into the same scope by means of a "using"
declaration.
V
BTW, same thing is possible to do without using the keyword "using".
This work in g++ and C++ Standard includes the correspondent syntactic
production (although I do not think the meaning of this kind of
declaration is explicitly explained anywhere in the Standard)
for example:
#include <cstdio>
using namespace std;
struct A {
virtual void foo() { printf("A::foo\n"); }
};
struct B : public A {
A::foo;
void foo(int i) { printf("B::foo, i=%d\n"); }
};
int main() {
B b;
b.foo();
b.foo(5);
}