Question

I've been looking on stackoverflow and google for a while now, but I can't seem to find an answer to my specific question about circular references, incomplete types and polymorphism.

I hope I can explain this question without posting a lot of code, but if I fail, please let me know and I will try to write down a simple example.

I have 2 classes, which both use each other (say class COne and CTwo). Also, class COne has a base class (say BaseOne).

I use header guards (if you call them that) and incomplete types to 'solve' the circular dependency problem.

in the header files on top:

#pragma once

and somewhere at the top in the C++ file for CTwo:

class COne;

Now I encounter the problem that, because of the incomplete type, the compiler does not seem to know that COne is derived from BaseOne. So in a function which has a return type BaseOne*, I want to return a COne*, which should be possible cause it's a downcast, but it says they are not of the same type. I have fixed this now using a C-style cast

return (BaseOne*)m_c_one;

What I wanted to ask: is there a better way to solve this then using a C-style cast?

Was it helpful?

Solution

The C-style cast is unsafe, because it is not guaranteed that the COne object and its BaseOne subobject have the same memory address (it is guaranteed if COne is a standard-layout class (9p7), but that generally precludes polymorphism).

The compiler needs COne to be complete to perform the cast (3.2p5) because COne could use virtual or multiple inheritance, and in general because polymorphic classes are not required to have a simple memory layout.

struct COne: BaseZero, BaseOne { ... };
struct COne: virtual BaseOne { ... };

You're going to have to either move the cast to a point in a source file where the definition of COne is available, or write your own casting function BaseOne *to_base(COne *) with an implementation at a point in a source file where the definition of COne is available.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top