How can I instantiate a class inside another class

  • Follow


Hello,

Here is my Code

class A
{
 int x;
public:
   A()
   {
       x=10;
   }
   A(int x_):x(x_){}
};

class B
{
 A a;
  B(){}
};

Now I want to call the second constructor of A (other than default
constructor) from B. IF there any possible way other than using
pointer variable?


Josekutty K K

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Reply kkjoseph 1/15/2005 2:52:56 AM

You can initialize in the member initializer.
class B
{
  A a;
  B() : a(10) {}
};

--lsu


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Reply L 1/15/2005 10:30:47 AM


kkjoseph@gmail.com (Josekutty K K) writes:

> class A
> {
>  int x;
> public:
>    A()
>    {
>        x=10;
>    }
>    A(int x_):x(x_){}
> };
>
> class B
> {
>  A a;
>   B(){}
> };
>
> Now I want to call the second constructor of A (other than default
> constructor) from B. IF there any possible way other than using
> pointer variable?

I am not sure what are asking for exactly, but

class B
{
  A a;
  B() : a(3) {}
};

uses the second A constructor to initialize a, and there is no
pointer variable involved.

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Reply Thomas 1/16/2005 4:22:28 AM

Josekutty K K wrote:
> class A
> {
>  int x;
> public:
>    A()
>    {
>        x=10;
>    }
>    A(int x_):x(x_){}
> };
>
> class B
> {
>  A a;
>   B(){}
> };
>
> Now I want to call the second constructor of A (other than default
> constructor) from B. IF there any possible way other than using
> pointer variable?

If I understand you correctly and you want to invoke A::A(int x_) from
B's constructor, do it whilst initialising B as follows:

class B
{
A a;
B() :
a(42)//or whatever value you require
{
    }
};


Rgds,
MikeB


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Reply MikeB 1/16/2005 4:23:12 AM

3 Replies
350 Views

(page loaded in 0.076 seconds)

Similiar Articles:













7/23/2012 1:40:56 PM


Reply: