Re: invalid covariant type / forward declaration?
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Sybolt de Boer wrote:
Robert Hairgrove wrote:
Sybolt de Boer wrote:
Considering the following situation, is there a way to tell class White
that a Black* is actually a valid Base*? In other words can I somehow
forward declare "class Black : public Base;" in White.h and vice versa?
Or am I trying to do something very bad and clearly illegal? :)
TIA, Sybolt
// Base.h
#ifndef BASE_H
#define BASE_H
class Base {
public:
virtual Base *colleague(int i) const = 0;
virtual Base *opponent(int i) const = 0;
....
};
// White.h
#ifndef WHITE_H
#define WHITE_H
#include "Base.h"
class White : public Base {
public:
White *colleague(int i) const { return White::create(i); }
Black *opponent(int i) const { return Black::create(i); }
static White *create(int i);
....
};
// Black.h
#ifndef BLACK_H
#define BLACK_H
#include "Base.h"
class Black : public Base {
public:
Black *colleague(int i) const { return Black::create(i); }
White *opponent(int i) const { return White::create(i); }
static Black *create(int i);
....
};
Move the function definitions into a .cpp file for each class. You will
also need to return Base* from both of the member functions in order for
it to work.
Thanks for your reply. This is a heavily synthesized example. In reality
the definitions are in a seperate source file. What I want is to preserve
to color of the opponent, and not immediately degrade to a Base*. My
compiler will allow me to include White.h in Black.h, or Black.h in
White.h, but not both at the same time. I hope I'm making myself clear
here. :)
I don't think this is possible. Black depends on White and White depends on
Black so you need to use a forward declaration. However, a forward
declaration cannot contain base specifier so covariant return type cannot be
applied.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
iEYEARECAAYFAksSiOsACgkQG6NzcAXitM8qUwCeL9fWiG4JXscydl+F0Nl3+bxs
PjkAnimnhIyGGVC/W71f8FUxZcuVnRuy
=O6DU
-----END PGP SIGNATURE-----