2

I have a class ID3 and a class Tree. An object of Class Tree is used in ID3 and its showing an error that Tree is not declared.

Code looks like

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <math.h>
#include <vector>
using namespace std;
class ID3 {
public:
      string v[];
      int x;
public:
     double Hi(Tree data)
    {
        int y=x-1;
    }
};
class Tree{
         Tree();
}
1
  • Note that string v[]; is not standard C++. Use vector<string> v; to make your code portable. Commented Mar 14, 2015 at 17:13

3 Answers 3

6

You need to forward declare Tree before using it in ID3, otherwise the compiler doesn't know what Tree is:

class Tree;

class ID3 {
...

If you need to use an instance of Tree somewhere then you need to have the full definition of Tree before that point, for example:

class Tree {
    Tree();
};

class ID3 {
...
    double Hi(Tree data) {
        // do something with 'data'
        int y=x-1;
    }
};

For more information about when to use forward declarations, see this Q&A.

Sign up to request clarification or add additional context in comments.

Comments

2

In general, C++ is compiled from top to bottom. So if the class ID3 needs the class Tree, Tree must be defined before ID3. Just put the class Tree before ID3 and it should be fine.

1 Comment

It doesn't need to be defined, it's enough to just declare it.
0

Forward deceleration of Tree will do the job. At the point where you used Tree instance in ID3, the compiler knows nothing about your Tree class, compiling process goes from up to bottom.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.