Tim
Tim

Reputation: 257

a class inherited from two class, with the same function prototype, conflict with each other

I am working on a Ray Tracing task, here is the problematic source:

class Geometry
{
    public:
        virtual RayTask *intersectionTest(const Ray &ray) = 0;
};

class Sphere : public Geometry
{
    public:
        RayTask *intersectionTest(const Ray &ray);
};

class BoundingVolume
{
    public:
        virtual bool intersectionTest(const Ray &ray) = 0;
};

class BoundingSphere : public Sphere, BoundingVolume
{
    public:
        bool intersectionTest(const Ray &ray) // I want this to be inherited from BoundingVolume
        {
            return Sphere::intersectionTest(ray) != NULL; // use method in Sphere
        }
};

source above can not compile, error information:

error: conflicting return type specified for ‘virtual bool BoundingSphere::intersectionTest(const Ray&)’
error:   overriding ‘virtual RayTask Sphere::intersectionTest(const Ray&)

I want to implement BoundingSphere::intersectionTest using method in Sphere, so I need to inherit from both BoundingVolume and Sphere. but due to inherit functions that has the same parameter list with different return type, things messed up...

I do not want to duplicate codes with the same functionality... could any one give me a solution?...

Upvotes: 4

Views: 921

Answers (1)

Patrick Niedzielski
Patrick Niedzielski

Reputation: 1214

The compiler is attempting to override two virtual methods with different return types, which isn't allowed: how would the compiler know how much memory to allocate for a function call if it doesn't know what the return type will be? The two methods cannot have the same names; try changing one to a more suitable meaning.

If you feel that these names best represent the meanings of the actions they both provide (which I'm not sure of), I would also suggest that you consider your hierarchies carefully. Is a spherical BoundingVolume really a Sphere? Perhaps not: it's implemented in terms of Sphere (private inheritance, doesn't solve your problem), or it has a Sphere (composition, would solve your problem in this simple case). The latter case, though, might present problems for move complex classes, where you want a BoundingSphere to have all the methods of Sphere. Or, perhaps, do you need to differentiate between BoundingVolumes and normal Geometrys?

Another solution to the problem would be to use non-member functions for one of these hierarchies, with Koenig lookup (the type of the argument) calling the proper version. I can't say without really knowing what your hierarchies look like. But do consider your design: if you have the same-named operation giving you back completely different semantic results, is the operation properly named/designed?

Upvotes: 1

Related Questions