Covariance Return in C++

M

mufenhsieh

I am testing covariance return in C++. First the following code
worked.

class A
{
public:
class X {};
virtual X* f() {return new X;}
};

class B : public A
{
public:
class Y : public X {};
virtual Y* f() {return new Y;}
};

int main(void) {
B b;
b.f();
}

However, after I modified it into template version, it couldn't
compile. Does anyone know how to make it work? Thanks.

template <typename Object>
class A
{
public:
class X {};
virtual X* f() {return new X;}
};

template <typename Object>
class B : public A<Object>
{
public:
class Y : public X {};
virtual Y* f() {return new Y;}
};

int main(void) {
B<int> b;
b.f();
}

Error messages:
test.cpp:20: error: expected class-name before '{' token
test.cpp: In instantiation of `B<int>':
test.cpp:25: instantiated from here
test.cpp:21: error: invalid covariant return type for `B<Object>::Y*
B<Object>::f() [with Object = int]'
test.cpp:11: error: overriding `A<Object>::X* A<Object>::f() [with
Object = int]'
 
V

Victor Bazarov

I am testing covariance return in C++. First the following code
worked.

class A
{
public:
class X {};
virtual X* f() {return new X;}
};

class B : public A
{
public:
class Y : public X {};
virtual Y* f() {return new Y;}
};

int main(void) {
B b;
b.f();
}

However, after I modified it into template version, it couldn't
compile. Does anyone know how to make it work? Thanks.

template <typename Object>
class A
{
public:
class X {};
virtual X* f() {return new X;}
};

template <typename Object>
class B : public A<Object>
{
public:
class Y : public X {};

There is no 'X' here. In templates base classes are not looked at
when resolving names. You need to prepend this definition with

using A<Object>::X;

or even

typedef typename A said:
virtual Y* f() {return new Y;}
};

int main(void) {
B<int> b;
b.f();
}

Error messages:
test.cpp:20: error: expected class-name before '{' token
test.cpp: In instantiation of `B<int>':
test.cpp:25: instantiated from here
test.cpp:21: error: invalid covariant return type for `B<Object>::Y*
B<Object>::f() [with Object = int]'
test.cpp:11: error: overriding `A<Object>::X* A<Object>::f() [with
Object = int]'

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top