Like Tree1Likes
  • 1 Post By grumpy

Help

This is a discussion on Help within the C++ Programming forums, part of the General Programming Boards category; I have Code: class A{ ... A(int x,int y){ } ... } class B{ A a; ....} in class B ...

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    51

    Help

    I have
    Code:
    class A{
    ...
    A(int x,int y){
    }
    ...
    }
    
    
    class B{
    
    A a;
    ....}
    
    in class B constructor, I want to initialize a with value 4 and 5.
    How can I do that?
    I tried this A a(4,5); but I dont think it is correct.

  2. #2
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,509
    Like this:
    Code:
    a = A(4,5);
    Manasij Mukherjee | gcc-4.8.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    51
    Quote Originally Posted by manasij7479 View Post
    Like this:
    Code:
    a = A(4,5);
    Maybe I typed something wrong in my code but that what I did initially but I have an error. Now I retyped it, it works lol

    Thanks.

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    51
    I am getting this error:

    IntelliSense: no default constructor exists for class "A"

    I am getting this error because I dont have an empty constructor for class A?

  5. #5
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,509
    Quote Originally Posted by byebyebyezzz View Post
    I am getting this error:

    IntelliSense: no default constructor exists for class "A"

    I am getting this error because I dont have an empty constructor for class A?
    Post the code please.
    Manasij Mukherjee | gcc-4.8.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,539
    Back to the OP, use an initialiser list in the definition of B's constructor.

    Assuming we're implementing B's default constructor.
    Code:
    B::B()  : a(4,5)
    {
         // job done
    }
    manasij7479 likes this.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy in reply to you, it is likely you deserve it. Suck it up, sunshine, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21