Overloaded Functions with Const

I have this function called productName that is overloaded but I don't know what is happening in the parentheses and after.
1
2
void productName(const std::string & productName)
std::string productName() const;
Last edited on
AlanB wrote:
I have this function called productName that is overloaded but I don't know what is happening in the parentheses and after.
void productName(const std::string & productName)
std::string productName() const;


You have this function productName ... which takes an argument productName. Are you sure?

const signifies that something is immutable (won't be changed or something nasty will happen to you).

Maybe you could give more context? Which particular "parentheses" and "after" are you referring to?


Primary uses of const:
https://en.cppreference.com/w/cpp/language/cv
https://en.cppreference.com/w/cpp/language/member_functions#const-.2C_volatile-.2C_and_ref-qualified_member_functions
Last edited on
In the first function I'm confused why there's a Ampersand which takes the arguement of the same name as the function. In the second function why is there a const after the function name?
Last edited on
I'm staggered that the first one compiles (but it appears to do so). I don't like it. I guess the compiler can distinguish between a function entity with () after it and a data variable.
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

void productName(const std::string & productName)
{
   std::cout << productName << '\n';
}

int main()
{
   productName( "This is a product" );
}



In the first case the ampersand in &productName means that the argument is "passed by reference". This has an effect similar to passing a single pointer and avoids the cost of a full copy of a potentially large object which would occur if it was passed by value. However, it also gives the function the undesirable opportunity to change the string object; qualifying it with const prevents that. The const here refers to the string productName itself.

In the second case the const is (presumably?) qualifying a member function of a class, stopping the function (inadvertently or deliberately) changing the data of an object of that class. The const here refers to the state of an object of that class.

I'm not going to take sides on the const-correctness debate. It depends whether you are writing your own simple software to "get the job done" or whether you are crafting highly secure code to prevent someone maliciously or carelessly screwing it up afterwards.
Last edited on
Thanks for that, I didn't know you can pass by reference.
Topic archived. No new replies allowed.