-2

In the code below, how do I instantiate the Side objects of the class Rectangle?

class Side{
    int l;
public:
    Side(int x){
        l=x;
    }
}

class Rectangle {
    Side a, b;
public:
    Rectangle(int s1, int s2){
         //How to initialize a and b?
    }
}
user1726
  • 65
  • 6

1 Answers1

9

All data members are instntiated as soon as you instantiate an object of the class they belong to. But you seem to be asking about initialization, or at least how to ensure that the data embers have a certain value after the constructor of the class that owns them has been called.

It would make the most sense to initialize the members in the constructor initialization list*:

Rectangle(int s1, int s2) : a(s1), b(s2) {}

Note that you can still modify the data members at any point after initialization. In this example, assignment is used:

a = Side(1);
b = Side(42);

* In this case, there is no option if you want to keep Rectangle's constructor, because Side has no default constructor. If you don't explicitly construct the members in the constructor's initialization list, their default constructor is implicitly called, so they must be default constructable.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • +1 for initializer lists rather than in the body of the constructor – Matt Coubrough May 26 '14 at 06:19
  • 2
    @MattCoubrough Initializing in the body would not work, because Side has no default constructor. – nwp May 26 '14 at 06:26
  • @nwp, exactly! hence the +1. – Matt Coubrough May 26 '14 at 06:27
  • I tried not using the initializer list and then putting `a = Side(1);` and `b = Side(42);` in the constructor `Rectangle()`, but then I get a "no matching call for Side::Side() error". Does this mean that `a` and `b` have not been instantiated because `Side` has no default constructor? – user1726 May 26 '14 at 06:35
  • 1
    @user1726 See the footnote. It doesn't mean what you think because the code didn't compile :-) – juanchopanza May 26 '14 at 06:38
  • @user1726 It means that `Side` requires a parameter to be constructed, but you did not give it one. You tried to provide a parameter in the constructor, but the member objects must have been created before the constructor is called. The initializer list is the way to provide parameters before the constructor is executed. It is a good practice to always do that, but in this case you have to. – nwp May 26 '14 at 06:42