Search⌘ K
AI Features

Discussion: A Strange Assignment

Explore the behavior of strange assignments in C++ by understanding how temporary objects are created from prvalues, how discarded-value expressions work, and how references bind to temporaries. This lesson helps you grasp core C++ mechanisms behind function calls, enabling better prediction of code outcomes and improved coding skills.

Run the code

Now, it’s time to execute the code and observe the output.

C++ 17
#include <iostream>
#include <string>
std::string getName()
{
return "Alice";
}
int main()
{
std::string name{"Bob"};
getName() = name;
std::cout << "Assigned to a function!\n";
}

Understanding the output

Wait, what? You can assign to a function? What does that even mean?

At first glance, it looks like we’re assigning a variable to a function call, which is the opposite of what we typically see (name = getName()). Let’s have a closer look at what’s going ...