Kristof Pal
Kristof Pal

Reputation: 1026

What is the c++ equivalent of this class definition

I am trying to learn C++ but my first language in Python. I am struggling a bit to understand the constructor in C++, and more specifically the variable size arrays and strings. Could someone write the C++ equivalent of the following class definition so I can follow the logic?

class Fruit(object):
    def __init__(self, name, color, flavor, poisonous):
        self.name = name
        self.color = color
        self.flavor = flavor
        self.poisonous = poisonous

Upvotes: 1

Views: 1497

Answers (1)

hlt
hlt

Reputation: 6317

class Fruit {
    std::string name;
    std::tuple<uint8_t, uint8_t, uint8_t> color; // for RGB colors
    std::string flavor; // Assuming flavor is a string
    bool poisonous;

    Fruit(const std::string& nm, const std::tuple<uint8_t, uint8_t, uint8_t>& clr, const std::string& flvr, const bool psns) : name(nm), color(clr), flavor(flvr), poisonous(psns) {}
}

The __init__ function does something very similar to a constructor in C++. Because in C++, you need to specify variable types, I took some liberty in assuming that name and flavor are strings, color is a 3-tuple of values from 0 to 255 (RGB) and poisonous is a boolean (bool) value.

Upvotes: 7

Related Questions