A struct inside a class?

Jul 23, 2014 at 12:53am
I'm getting confused.

If I have a class declared in class.h and defined in header.h like below.
I'm just not sure how it is implemented and accessed.

class.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class myclass
{
public:
int a;
int b;
myclass(a,b);
~myclass();

//somewhere in here I put my structure like below.
struct mystruct
{
int x;
int y;
}instance;

};


class.cpp

myclass::myclass(int,int):a(5),b(4){}


main.cpp
1
2
3
4
5
int main()
{
//I'm not sure how I would access this struct?  Completely lost actually?
//is my syntax in the class declaration right?
} 
Last edited on Jul 23, 2014 at 12:53am
Jul 23, 2014 at 1:58am
I think,
myclass(a,b); >> myclass(int,int);

myclass::myclass(int,int):a(5),b(4){} >> myclass::myclass(int aa,int bb):a(aa),b(bb){}


First thing, did you success linked all files you build ? Do they work together?

If you did,
now you'll have class named MYCLASS that consists of INTs and MYSTRUCT element named INSTANCE in it.

You just have to create object from class MYCLASS, assume named myobject.

myclass myobject(5,4);

now you have,
1
2
3
4
myobject.a
myobject.b
myobject.instance.x
myobject.instance.y
Last edited on Jul 23, 2014 at 1:59am
Jul 23, 2014 at 2:50am
I'm still confused.
I'm talking about placing a struct inside a class?, how do do it and how to access it?

The last step seems to be covered.
Jul 23, 2014 at 3:13am
Your code already makes you able to do that, doesn't it?
What's your real problem? Just want to know how other people do?

If it's, there's the way I'll do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
typedef struct mystruct{
    int aa;
    ...
}mystr;

class mycl{
public:
    mystr a;
    int b;
    ...
};

int main(){
    mycl myobject;
    myobject.b = 10;
    myobject.a.aa = 100;
}
Last edited on Jul 23, 2014 at 3:18am
Jul 23, 2014 at 4:03am
I see what you have done here. Is it possible to define the structure inside a class or is it just not practical to do so?
Last edited on Jul 23, 2014 at 4:05am
Jul 23, 2014 at 4:04am
I'm not sure how I would access this struct?

You have a class member called instance, which you can access using class member access operator . (dot), and you have a nested type called mystruct, which you can access using the scope resolution operator ::

1
2
3
4
5
6
int main()
{
    myclass c(1,2);
    c.instance.x = 7;
    myclass::mystruct another_instance = c.instance;
}
Jul 23, 2014 at 4:15am
Okay, I see.
Like Cubbi said, you can use :: to access what you declared in the class.

But I didn't use it too much, then sorry that I misunderstand it.
Usually, I'll use namespace or just create struct outside and call it as an instance in class.

Because in class, I think what's in it should be default private so class does everything itself. if outside want to do something, they have to call by functions.
Topic archived. No new replies allowed.