Class in Class

How can this code compile?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using std::cout;
using std::endl;

class CBox                             // Class definition at global scope
{
  public:
    double m_Length;                   // Length of a box in inches
    double m_Width;                    // Width of a box in inches
                   // Height of a box in inches
	
double function()
{
	CBox a;
	m_Height = 15;
	return m_Height;
	}

 double m_Height;   
};

int main()
{
  CBox box1;                           // Declare box1 of type CBox                         

  cout<<box1.function()<<endl;

  cout << endl;
  return 0;
}


You have not defined m_Height so how can you set it to a value, or even know its there?

And why can you declare the same class within that class as being done here?

Isnt CBox a incomplete type?


Why cant you put the same class as a member of itself then?
Last edited on
What compiler are you using?
Visual C++
This explains very well why you cant have a CBox or a class as a member of itself VERY WELL

http://answers.yahoo.com/question/index?qid=20101228143726AALgIAt

This post:



------------------------------------------------------------------------------------------------

"I think the problem for you is that you're creating them inside the constructor. It's sort've like an indefinite recursion if you think about it. When you create a Person object in another class the constructor is automatically called. That constructor creates another Person object (father/mother). However, since you're creating another Person object then the constructor for that person object is getting called which, you guessed it, creates another Person object(father/mother again) and so on and so on until your computer blows up (or just gives the error message :)

I believe if you create some method that creates a Person object then it would work fine. Just take it out of the constructor.

Or better yet, take advantage of inheritance. Create a subclass of Person called Parent or something."

------------------------------------------------------------------------------------------------




Although why can you do it in function makes sense now, because it is not necessarily creating a new type of CBox every time its constructor is called/CBox is created, only when the function is called.

Although my first question has remained unanswerd so I am trying to find a answer to that.

Any help would be appreciated!
Last edited on
Because a class is a collection objects, and not a sequential program. When the program access the variable, it.tiff resolves the address of the class, then the object.
Oh ok thanks!
Topic archived. No new replies allowed.