Today, I faced very weird problem. I have 2 classes say class A and B. Both have one .h and .cpp files. 4 files(A.cpp,B.cpp,A.h,B.h). A class is base class of B and we are using instance of B in class A. It was saying "not a type" error while compiling. How can I solve the error? Google was saying "it is a kind of cyclic dependency" in the code that's why it was giving error. Please help. Thanks.

you have to use forward declarations and pointers.

A.h

#ifndef A_H
#define A_H
class B;

class A
{
private:
    B* bclass;
public:
    //...
};
#endif

A.cpp

#included "A.h"
#included "B.h"

// code for class a goes here.

B.h

#ifndef B_H
#define B_H
#included "A.h"

class B : public A
{
    //...
}
#endif

B.cpp

#include "B.h"

// code for class goes here

Change #included to #include

@moschops That's ok. This might be typo nothing else.

If I have to use Instance of B in A.h rather than pointer then? I know we cant define any instance for the forward declaration, but what is the solution in that case? Thanks.

First I want to apologize for #included instead of #include. I am not sure why I did that. Secondly when dealing with an incomplete type which is what a forward declaration of a class gives you you are only allowed to do certain things. There is a nice explanation on SO that you can find here.

As a side note and maybe a moderator can give me an answer if there is a post on SO that has a nice answer to a question should we just link to it or is it okay to copy it. I normally link to it since I dont want to pass of their post as my own but now with a the whole SEO thing going on I wasnt sure it we should copy it.

If I have to use Instance of B in A.h rather than pointer then? I know we cant define any instance for the forward declaration, but what is the solution in that case? Thanks.

You cannot do that, it's a physical impossibility. One way or another, you cannot have the definition of A being dependent on the definition of B and also have the reverse. You have to find a way to make things work with only a forward declaration, or put all A's code that needs B into the A.cpp file and include B.h in that cpp file. There are some tricks here and there, but we need to know more about the actual design to help you with that.

if there is a post on SO that has a nice answer to a question should we just link to it or is it okay to copy it.

Linking is better than copying/quoting it. I generally try to avoid doing just a link though. Try to provide your own answer, or a summary in your own words, with the SO link as more of a "read more here" type of link. The general idea is that the discussions here should be coherent without having to follow the links.

Thanks for the guideline Mike. You are informative as always.

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.