Constructor of Class within a class

I've to define a class within a class something like this:
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
class A
{
    int a;

    public: 
     A ();
}

class A::A()
{
    a = 100 ; 
}

class B
{
   class A a1 ;
   int b ;

   public:
    B (int b, int a);
}

class B::B(int b, int a)
{
    this->b = b ;
}

As of now, member "a" of class A is initialized to 100 (line 11) in the constructor when object B is created.
But, is there any way to initialize "a" of class A with argument "int a" sent to the constructor of class B instead of hardcoding to 100?
Use initializer lists:

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
class A
{public:
    int a;

    public:
     A (int a);
};

A::A(int a) // class keyword not required here
{
    this->a = a ;
}

class B
{
   class A a1 ;
   int b ;

   public:
    B (int b, int a);
};

B::B(int b, int a) :a1(a) // <---- initializer list
{
    this->b = b ;
}

int main()
{
B b(0,100); // B::a1.a will be equal to 100
}

Topic archived. No new replies allowed.