1

This is a program that uses classes, together with parameter constructors.

#include <string>

class Ball {

private:
    std:: string m_color;
    double m_radius;
public:

    Ball(const std::string& color, double radius)
    {
        m_color = color;
        m_radius = radius;
    }

    void print()
    {
        std::cout << "color: " << m_color << std::endl;
        std::cout << "radius: " << m_radius;
    }

};

int main()
{
    Ball blueTwenty{ "blue", 20.0 };
    blueTwenty.print();

    return 0;
}

Why do we have to add const before our first parameter? I see that the double-type parameter doesn't need one. Also, why do we need the first address of the parameter (I guess this is the reason for including &)? Could anyone explain the logic behind?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 8
    Sounds like you could use a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Apr 08 '20 at 17:40
  • The copy operator `std::string::operator=` expects a `const std::string&` which could otherwise be just used as a simple `std::string` if the string were to be modified anywhere inside the scope of constructor. This is not considered to be necessary but is a good habit to get into. – Ruks Apr 08 '20 at 17:44
  • 1
    "why do we need the first address of the parameter" - Remember that C++ is a *context sensitive* language. `&` means different things in different contexts. It doesn't always mean "address of", here it means "reference" - it can also mean "bitwise and" in other contexts. – Jesper Juhl Apr 08 '20 at 17:46

1 Answers1

3

It's not that it doesn't need one, but that the const was omitted. Changing radius won't impact the caller, but color, as a reference, could. Technically they should both be const unless they need to be modified.

const just says "I promise not to modify this argument" which the compiler can interpret a number of ways, including making optimizations in the code based on that.

It also avoids inadvertent mutation of arguments which can cause unpredictable side-effects.

tadman
  • 208,517
  • 23
  • 234
  • 262