I decided to see if assigning a reference to a member would make a member a reference. I wrote the following snippet to test it. There's a simple class Wrapper
with an std::string
as a member variable. I take take a const string&
in the constructor and assign it to the public member variable. Later in the main()
method I modify the member variable but the string
I passed to the constructor remains unchanged, how come? I think in Java the variable would have changed, why not in this code snippet? How exactly do references work in this case?
#include <iostream> #include <string> using namespace std; class Wrapper { public: string str; Wrapper(const string& newStr) { str = newStr; } }; int main (int argc, char * const argv[]) { string str = "hello"; cout << str << endl; Wrapper wrapper(str); wrapper.str[0] = 'j'; // should change 'hello' to 'jello' cout << str << endl; }
Constructors can be passed as arugments to methods using a method reference, somewhat like a function pointer in C++. This can be a Function type with one argument or a BiFunction type with two arguments, either way its a lambda returning a class of the type it constructs.
You can pass an argument of any data type into a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as classes and arrays.
A copy constructor defines what copying means,So if we pass an object only (we will be passing the copy of that object) but to create the copy we will need a copy constructor, Hence it leads to infinite recursion. So, A copy constructor must have a reference as an argument.
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.
To assign a reference in a constructor you need to have a reference member
class A{ std::string& str; public: A(std::string& str_) : str(str_) {} };
str is now a reference to the value you passed in. Same applies for const refs
class A{ const std::string& str; public: A(const std::string& str_) : str(str_) {} };
However don't forget that once a reference has been assigned it can not be changed so if assignment requires a change to str then it will have to be a pointer instead.
Because Wrapper::str
is not a reference, it's an independent object. So when you do str = newStr
, you're copying the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With