class inside a class?

I'm trying to write a class definition inside another class definition but I'm having some trouble. It's easy when putting them all in the same file but when placing them in the arrangement below I can't seem to figure out how it should be accessed in main. How do I arrange the below so it will output the variables in class1 (inside class2) in my main function.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65


CLS.H

#ifndef CLS_H_INCLUDED
#define CLS_H_INCLUDED

class class2
{
    public:
        class2();
        int a;
        int b;
    class class1
    {
    public:
        int x = 7;
        int y = 12;

    };
    
    class1 cl;
};

#endif // CLS_H_INCLUDED




CLS.CPP

#include <iostream>
#include <cstdlib>
#include "cls.h"


using namespace std;



class2::class2()
{
    a = 7;
    b = 9;


}



MAIN FUNCTION
#include <iostream>
#include "cls.h"

using namespace std;

int main()
{
   class2 myclass();


   cout << myclass.cl.x << endl;
   cout << myclass.cl.y << endl;
}
Last edited on
Define class1 before and outsider of class2, then put an instance of class1 inside class2.
You're accessing it correctly.

The problem is on liine 59. What you're doing there is declaring a function that returns an object of type class2. Remove the ().

By the way: class1 can be accessed so class2::class1 myclass1;
Thanks coder, got it now.
Topic archived. No new replies allowed.