creating class objects in a header file

Why does it seem impossible to create an object inside a header file of another class(made in a header file).
It's not. Here's a working example.

1
2
3
4
5
6
// first.h

class firstClass
{
  int a;
}


1
2
3
4
5
6
7
8
// second.h

#include "first.h"

class secondClass
{
  firstClass b;
}


1
2
3
4
5
6
7
8
// main.cpp
#include "second.h"

int main()
{
secondClass b;
return 0;
}




i didn't mean that. I mean instead

1
2
3
4
5
6
// first.h

class firstClass
{
  int a;
}



1
2
3
4
5
6
7
8
9
// second.h

#include "first.h"
 firstClass b;//I declared it in the global space
class secondClass
{
b;
 
}



1
2
3
4
5
6
7
8
// main.cpp
#include "second.h"

int main()
{
secondClass b;
return 0;
}


Error output
copy\open gl snake game\food.h(12): error C2146: syntax error : missing ';' before identifier 'qaLight_M'
//
Last edited on
I'm being told by VC2010 that, there are no members available, this is inside the header file
Last edited on
This

1
2
3
4
class secondClass
{
  firstClass b;
};


is defining what an object of type secondClass looks like. When you are defining what an object looks like, you can specify member variables and member functions.

I don't understand, its preventing me from initiating an object in the second class
Don't forget the trailing semi-colon after your class definitions.

The definition of a class is essentially an explanation to the compiler of what to make when you create an instance of that class.

You define the class, like this for example:

1
2
3
4
5
class someClass
{
  int a;
  double b;
}


The compiler see this, and now knows that there is a new type, named a someClass, and it contains an int called a and a double called b. You have not created an object; just explained to the compiler how to make one.

Now, you can create objects of type someClass like this:

1
2
someClass instance01;
someClass instance02;


When you write this:

1
2
3
4
5
class secondClass
{
b;
 
};


you are saying there is this new kind of object, and we're going to call this new kind of object an object of type secondClass, and then you're saying it contains a 'b'.

The compiler has no idea what an object of type 'b' is. The error I get is:

ISO C++ forbids declaration of ‘b’ with no type


This explains how to define and than create an instance of a class: http://www.cplusplus.com/doc/tutorial/classes/

Out of interest, are you a Java coder?




Last edited on
this is the most awkward problem, i've ever experienced itusually works but it not in this instance
I'm making an Open GL project but I don't get why this works in console but not glut
I don't get why this works in console


You said it didn't work.
thats really weird for me, I guess there must be some other error
Topic archived. No new replies allowed.