0

I am a beginner in c++. I am not much aware about the the usage of maps or other stl containers. In my program I have defined one class group and one map<int,group>mymap

Its a very long code and most of it is irrelevant so i am giving a small part of it which is as follows:

map<int, group>idgroup;
class group;    //forward reference

class user
{
private:
  int w;
  int d;
  float p;
public:
  int present_gid;
  friend void calcprice(int*, int);

}c[50];

class group
{
  private:
  int g_id;
  int td;

public:
  vector<int>members;
  group* next;

  group()
  {
    td = 0;
    next = NULL;
  }
}

void calcp(int* id, int n)
{
  int gid,Td;
  float p=0.01,q=0.1,r=8,cpu;
  for(int i=0; i<n; i++)
  {
    gid = c[id[i]].present_gid;
    group g = idgroup.find(gid)->second;
    Td = g.td;
    cpu = (p*pow(Td,2) + q*Td + r)/Td;
    c[id[i]].p = cpu*c[id[i]].d;
  }
}

int main()
{
  int n;
  cin>>n;
  int *grp_id = new int[n];
  calcp(grp_id, n);
  return 0;
}

When I give the map declaration before the class I get the following error:

error:‘group’ was not declared in this scope map<int, group>mymap;

and when I give a forward declaration of the class, I get the following error:

error: forward declaration of ‘class group’ class group;

I am not able to understand what is the problem. Please help. Thank you!

4
  • 1
    Are you sure the second error doesn't being with "error: invalid use of incomplete type"? Commented Jun 21, 2014 at 6:19
  • 2
    Show more of your code and give the actual error messages. Is mymap a field inside group ? Commented Jun 21, 2014 at 6:20
  • @jposeph yes it comes with "error: invlid use of incomplete type" Commented Jun 21, 2014 at 6:29
  • A declared (as opposed to defined) type is incomplete and can not be used as value type in std::map (and other containers). You have to fully define the class before you can create a map of it, a (forward) declaration isn't enough. Commented Jun 21, 2014 at 8:01

1 Answer 1

1

I think you have to solutions depending on the context.

  1. Keep forward declaration for group class as is, and declare your mymap like std::map < int, group *>. Having a pointer type would be problematic in your code. Depends on the context.

  2. Remove forward declaration and include the header file which contains the declaration of class group. It seems this may be a fair solutions for you. Again depends on the context. If have to hide header file inclusion to optimize compile time efficiency. This is not suitable.

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

1 Comment

all my class declarations are in the same file.

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.