Composition QUESTION

Hi, may I know if there is a way to B object without calling A object beforehand?
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
34
35
36
37


class A{
   private:
       int attackPower;
   public:
      void setPower(){
           cout<<attackPower;
       }
    
   A(int a)
   {
       attackPower=a;
   }
};

class B{
   private:
      A eob;
   public:
      B(A ee)
      :eob(ee)
   {	
   }
   void show()
      {
         eob.setPower();
      }	
};

int main()
{
      //A obj(1); What if I never declare this first?
      B no(obj); //Is there a way to call B object(which has A object as 
                     //private variable)
      no.show();
}
Last edited on
If you want to be able to create an object of type B without passing in an object of type A, then you need to define a default constructor.

Also, I strongly encourage you to adopt a sensible indentation style. It will make it much easier to see the structure of your code, and will help you spot errors more easily.
Last edited on
Thanks for your reply and sorry for not having indentation for the codes(I haf fixed it). May I know how to define a default constructor?Thank you.
A default constructor is just a constructor that doesn't take any arguments. You define it the same way as you'd define any other constructor.
I don't quite understand it.Could you rewrite my code with default constructor? I would really appreciate it! Thanks!
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
34
35
36
37
38
39
40
41
42
#include <iostream>

class A {

   private: int attackPower;

   public:

       explicit A( int ap ) : attackPower(ap) {}

       void show() const {

           std::cout << "A { attackPower == " << attackPower << " }\n" ;
        }

       // ...
};

class B {

   private: A eob;

   public:

      explicit B( A a ) : eob(a) {} // copy construct eob

      explicit B( int ap ) : eob(ap) {} // construct eob with attack power ap

      // ...

      void show_eob() const {

          std::cout << "B::eob: " ;
          eob.show() ;
      }
};

int main() {

    const B bb(23) ;
    bb.show_eob() ;
}

http://coliru.stacked-crooked.com/a/628cae50f62368a9
I'm not going to write your code for you.

You already know how to write a constructor that takes arguments, because you've already done that in both your classes.

You already know how to write a function that takes no arguments, because you've already done that in both your classes.

What is confusing you about writing a constructor that takes no arguments?
Last edited on
Topic archived. No new replies allowed.