May 22, 2015 at 5:36am May 22, 2015 at 5:36am UTC
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 May 22, 2015 at 5:36am May 22, 2015 at 5:36am UTC
May 22, 2015 at 6:09am May 22, 2015 at 6:09am UTC
Define class1 before and outsider of class2, then put an instance of class1 inside class2.
May 22, 2015 at 6:31am May 22, 2015 at 6:31am UTC
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;
May 24, 2015 at 9:38am May 24, 2015 at 9:38am UTC
Thanks coder, got it now.