Classes initilizing query

closed account (zybCM4Gy)
Hi, have recently broken into the classes I tutorial. (Took meh long enuf!) Unfortunately I'm having a bit of a dilemma.

At the moment I have understood that ALL variables should be initialized with a default value (I've had a number of unexpected problems...and I have lots of sources from various places telling me I should always init). Anyway I have the following class...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using shorty = unsigned short int;

class Squirt_bottle
{
    private: //Private is default anyway.
        shorty current_volume_ml = 0;
        shorty max_volume_ml = 750;

    public:
        //Fill it up with how much water?
        void set_value(shorty);
        shorty remaining_volume(void)
        {
            return (max_volume_ml - current_volume_ml);
        }
};


Now obviously I have already initialized the values with absolute basics... so...what's the point of a constructor class? Wouldn't my default values apply anyway?
closed account (zybCM4Gy)
... -_-;;;

Right, the answer to my question is something along the lines of....

It's all good that you're creating something with already initialized values. However, what if you want to create a new object that has different initialized values? This is the reason why it is useful to have a constructor.

so I could create a squirt bottle that is smaller or larger depending on my needs.

1
2
3
4
5
Squirt_bottle::Squirt_bottle( shorty a, shorty b )
{
    current_volume_ml = a;
    max_volume_ml = b;
}


As my code currently stands I would be unable to change the bottle size at all since it's not possible in set_value... which I should probably rename to fill_bottle but never mind.
Also, note that directly initialising data members in the class definition, as in:

1
2
3
    private: //Private is default anyway.
        shorty current_volume_ml = 0;
        shorty max_volume_ml = 750;


is a new feature of C++11, so you couldn't do that in earlier standards.
closed account (zybCM4Gy)
These feature changes really need to be outlined more clearly. I had no idea that it was a C++11 thing, which means that a constructor would have been absolutely necessary.

Thanks for that.
Topic archived. No new replies allowed.