Class question

I have the following two classes:

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 Plant {
private:
    string name;
    string location;
    int sensorId; //sensor ID
    double humidityMin; //Planten trenger vann om den blir tørrere enn denne verdien
    double humidityMax; //Planten er for våt over denne verdien
    double humidity; //Sist leste fuktighetsmåling
    
public:
    Plant(string name, string location, int sensorId, double humidityMin, double humidityMax, double humidity = -1) : name{name}, location{location}, sensorId{sensorId}, humidityMin{humidityMin}, humidity{humidity} {}
    void setName(string plantName) {
        name = plantName;
    }
    string getName() {return name;}
    string getlocation() {return location;}
    //double readHumidity();
    PlantStatus getStatus();
    bool operator==(Plant& rhs);
    string plantStatusText();
    
    
};


class Garden {

private:
    string name;
    vector<Plant> plants;
public:
    Garden(string name);
    void addPlant(Plant p);
    void removePlant(Plant p);
    vector<Plant> needsHelp();
    
};


When looking at the solution manual, there was an entry in the initialization list of the Garden constructor I didn't understand (bold part):

[code]
Garden::Garden(string name) : name(name), plants() {}

Can anyone help?
Last edited on
That calls explicitly the default constructor of the std::vector<Plant>. The constructor would do the same thing even if the member initializer list would omit that call.
Thank you! but what exactly will it do?
it constructs a vector. That may or may not allocate some plants as a side effect (not sure if it immediately makes memory or waits on the first element to be added). So it sets the internal size variable to zero and whatever a vector does to itself when created.

try this in your plant constructor.
Plant ( stuff)
{
static int p = 1;
cout << "created plant # " << p++;
}

and in main, make a vector of plants like you do in garden and play with it.
try an empty one, see what it does. then try a push-back on it, see what that did.
try a preallocated one vector<plant> vp(100);
and whatever you want to do to see if you can get enlightenment as to what is going on.

Thanks!

when you create a vector in a class, does the constructor of your class always call a default vector constructor?
Topic archived. No new replies allowed.