Class reference to parent

c++, class, oop, parent-child

Solution

Forward-declare `B` and `C`. This way compiler will know they exist before you reach the definition of class `A`.

class B;
class C;

// At this point, B and C are incomplete types:
// they exist, but their layout is not known.
// You can declare them as function parameters, return type
// and declare them as pointer and reference variables, but not normal variables.
class A
{
    ....
}

// Followed by the *definition* of B and C.

P. S.

Plus, one more tip unrelated to the question (seeing how you come from a C# background): it's better to pass by const reference than by value:

class A
{
...
    void DoSomething(const B& par1);
    void DoSomething(const C& par1);
...
}

Problem

i'm pretty new at using C++ and I'm actually stopped at a problem. I have some class A,B,C defined as follow (PSEUDOCODE) ``` class A { ... DoSomething(B par1); DoSomething(C par1); ... } class B { A parent; ... } class C { A parent; ... } ``` The problem is : How to make this? If I simply do it (as I've always done in c#) it gives errors. I pretty much understand the reason of this. (A isn't already declared if I add the reference (include) of B and C into its own header) Any way to go around this problem? (Using void* pointer is not the way to go imho)

Original source

Related problems