Search code examples
c++oopconstructorprivate

Constructor setting all values to 0


So from an assignment I have from school, I have to make a default constructor that is supposed to set all floats and ints to 0 and all strings to "NA".

Earlier it was pretty easy I had to just do a constructor to set volume to 0, calories to 0 and etc.

My question is,

How does the syntax for setting all floats, and ints to 0 and trying to get strings to all say "NA"?

This is what I had so far

class Candy {
private:
    float sweetness;

protected:
    string color;

//CONSTRUCTOR//

    void setName(string n);

    void setFloat(float f);

    void setInt(int i);

This is on another cpp file we have to do.

Candy::Candy() {

Candy(string n) {
    setName(n);
}

Candy bo("NA");
}

Am I in the right direction? I am really new to this, and I am not very good with syntax. Thanks!


Solution

  • Use the constructors initialization list:

    class Candy {
    private:
        float sweetness;
    
    protected:
        string color;
    
    public:
        Candy() : sweetness(0.0f), color("NA") { }
    };
    

    Or (in C++11 or later), use in-class initializers:

    class Candy {
    private:
        float sweetness = 0.0f;
    
    protected:
        string color = "NA";
    
    public:
        Candy() = default;
    };