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?

Recommended Answers

All 4 Replies

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.

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.

//////////////////// 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

Thank you very much. That worked perfectly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.