const correctness C++


  • Gesperrt

    which is correct option here?

    Below code is not compiling. Which of following changes can be made to correct problem and maintain const correctness?

    `` cpp

    class Cart {
    bool bCountValid;
    int fruitCount;

    static int apples;
    static int oranges;

    public:
    Cart() : fruitCount(0), bCountValid(false) {}

    void addApples(int a) { apples += 1; bCountValid = false;}
    void addOranges(int o) { oranges += o; bCountValid = false;}

    int getItemCount() const {
    if(!bCountValid) { fruitCount = apples + oranges; bCountValid = true; }
    return fruitCount;
    }

    };

    int Cart::apples = 0;
    int Cart::oranges = 0;

    int main(int argc, char**argv)
    {

    Cart const checkoutPerson;
    Cart shopper;

    shopper.addApples(2);
    shopper.addOranges(7);

    int total = checkoutPerson.getItemCount();
    }

    1)Remove const qualifier from member function getItemCount()
    2)Declare the shopper object to be of type Cart const rather than of type Cart.
    3)Make members apples and oranges mutable
    4)Make members apples and oranges non-static members
    5)Make members bCountValid and fruitCount mutable
    ``


  • Gesperrt

    @tampere2021 sagte in const correctness C++:

    Make members apples and oranges mutable

    Make members apples and oranges mutable?



  • Make fruitCount and bCountValid mutable



  • The real question is: what is the intended behavior of this code? In particular: why does a Cart have static variables apples and oranges? Why is the parameter a ignored?

    So the only correct answer to "Which of following changes can be made to correct problem" is "Design your classes properly".


Anmelden zum Antworten