How to create a class object inside another class?

My thought is that I would need to establish a variable for the class in the header and call the class within the .cpp file

1
2
//class A.h
B b;


Then in class A, to create the object and use a method from the object I would -

1
2
3
4
5
6
7
8
//class A.cpp
A::A(){
b();
}

int someAmethod(){
     b.bmethod();
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct B
{
    B(int x, int y)
    : x(x)
    , y(y)
    {
    }

    void set(int a, int b)
    {
        x = a;
        y = b;
    }

private:
    int x, y;
};
1
2
3
4
5
6
7
8
struct A
{
    A();
    void f();

private:
    B b;
};
1
2
3
4
5
6
7
8
A::A()
: b{0, 0}
{
}
void A::f()
{
    b.set(1, 1);
}
Last edited on
I'm not familiar with structs using functions. Having :b{0,0} after () and before {} seems very odd to me. Not sure what is happening there.
I am trying to it, then I will upload here with complete solution.
There is no difference between the struct and class keywords in C++, aside from default privacy settings.

The stuff between the constructor parameter list and body is called an initializer list - it is where you need to initialize the members of your class.
Last edited on
I am not getting you.



//file A.h

?? contain

//file A.cpp

?? contain
LB thanks for explaining that. I had done some work in C and of course did not use functions in my structs.

sujitnag - I was trying to figure out how to use a class object inside another class.
Last edited on
Topic archived. No new replies allowed.