Covariants

N

Noah Roberts

I got a question about covariants and overloading. This is my code:

#include <iostream>
using namespace std;

class Parent1
{
};

class Parent2
{
public:
virtual Parent1 * f() { return new Parent1(); }
};

class Child1 : public Parent1
{
public:
class Child2 : public Parent2
{
public:
Child1 * f() { return new Child1(); }
};
};

int main()
{
int x;
cin >> x;
}

This code refuses to compile saying that overload of f() returns
non-covariant of Parent2::f()'s return.

This change compiles fine:

class Child1 : public Parent1
{
public:
};
class Child2 : public Parent2
{
public:
Child1 * f() { return new Child1(); }
};

As does this:


template<class T>
class Child1 : public Parent1
{
public:
class Child2 : public Parent2
{
public:
Child1 * f() { return new Child1(); }
};
};

int main()
{
Child1<int> c;
int x;
cin >> x;
}


I thought that any inner class had access to all names the outer class
does. The outer class knows what it is, why doesn't the inner class
know what the outer class is? Obviously Parent1 is not fully defined
when declaring Child2::f() but what is the rule I'm breaking in the
first example?
 
V

Victor Bazarov

Noah said:
I got a question about covariants and overloading. This is my code:

#include <iostream>
using namespace std;

class Parent1
{
};

class Parent2
{
public:
virtual Parent1 * f() { return new Parent1(); }
};

class Child1 : public Parent1
{
public:
class Child2 : public Parent2
{
public:
Child1 * f() { return new Child1(); }
};
};

int main()
{
int x;
cin >> x;
}

This code refuses to compile saying that overload of f() returns
non-covariant of Parent2::f()'s return.

Really? Comeau compiles it fine, so does VC++ v8.
This change compiles fine:

[..]

I thought that any inner class had access to all names the outer class
does. The outer class knows what it is, why doesn't the inner class
know what the outer class is? Obviously Parent1 is not fully defined
when declaring Child2::f() but what is the rule I'm breaking in the
first example?

The compiler you're using is obviously buggy.

V
 
V

Victor Bazarov

Noah said:
For what purpose. I don't need to be told to go post elsewhere. My
question was on-topic.

I am sorry, I didn't mean to suggest you were off-topic. I just pointed
you to that newsgroup because they know better about the differences between
v7 and v7.1 (if you don't want or can't upgrade). Lighten up, will you?
It is quite possible that an upgrade to 7.1 is free (again, I don't know,
but m.p.vc.l frequents might).

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top