0

Hello, everyone! I just have a simple question, I think. I have created three unique classes, and each of these classes use some of the others as member variables. However, because of the way the code is organized, I often receive the error "CLASSNAME is not declared" when trying to compile.

For the sake of a concise example, here's code based on my own that gives me an issue.

class A
{
    private:
        [...]
    public:
        [...]
        void setInfo(int age, C *ptrToC);
};

class B
{
    private:
        A exampleofA;
    public:
        [...]
};

class C
{
    private:
        int age;
        A secondexampleofA;
        B exampleofB;
    public:
        [...]
};

As you can see, class A has a pointer to class C, but it returns an error becuase class C has not been created yet. However, I cannot simply move class A down the list because class B depends on class A as well and moving it would cause errors. So what should I do?

3
Contributors
4
Replies
5
Views
4 Years
Discussion Span
Last Post by bladelord76
1

You want to do something called forward declaration. So before your class definition of class A, simply type:

class C;
class A {
    ...
}

Essentially it's similar to function prototypes where it says this class exists, and the definition will come later.

0

Thank you! That does help, and it works and compiles then. However, when I try something like...

class A
{
private:
[...]
public:
[...]
void setInfo(int age, C *ptrToC);
};

void A::setInfo(int age, C *ptrToC)
{
    ptrToC->randomFunction(); // presuming the function in question has been created below...
}

[...]

Then it gives me the same error as before. Can you not use forward declaration when you include functions like that?

EDIT: Specifically, that error usually comes out as "error: invalid use of incomplete type 'Struct C'" followed by "error: forward declaration of 'struct C'" while using the mingw g++ compiler.

Edited by bladelord76

1
//////////////////// a.h //////////////////////////

class C ;

class A
{
    public:
        void setInfo(int age, C *ptrToC);
};


//////////////////// b.h //////////////////////////////

#include "a.h"

class B
{
    private:
        A exampleofA;
};


//////////////////// c.h /////////////////////////////////

#include "b.h"

class C
{
    public:
        void randomFunction();
    private:
        A secondexampleofA;
        B exampleofB;
};


/////////////////////// a.cc //////////////////////////

#include "a.h"
#include "c.h"

void A::setInfo( int age, C *ptrToC )
{
    ptrToC->randomFunction(); 
}

Note: #include guards etc. elided for brevity

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.