Home » Community » Newbie corner » differences in returns between pointer and reference
differences in returns between pointer and reference [message #56940] |
Sun, 02 May 2021 17:18 |
BetoValle
Messages: 203 Registered: September 2020 Location: Brasil Valinhos SP
|
Experienced Member |
|
|
Hi,
as a novice in c ++, put down some interesting returns of variable values between "pointer" and "reference" alternating.
if possible, I ask that the experts express about the only one that does not return value is the struct abc!
struct abc{
String b;
public:
abc( String& xx){
b=xx;
}
void fecha(){
b="retornado"; // this not return: reference constructor is address
}
~abc(){};
};
struct de{
String* b;
public:
de( String* xx){
b=xx;
}
void fecha(){
*b="retornado"; // this return: reference constructor is pointer
}
~de(){};
};
void rotina1( String &s )
{
s="123";
}
void rotina2( String *s )
{
*s="yyy";
}
CONSOLE_APP_MAIN
{
String st="abc";
rotina1(st);
Cout() << "after rotina1: " << st << EOL;
String* a = &st;
rotina2(a);
Cout() << "after rotina2: "<< *a << EOL;
abc c(*a);
c.fecha();
c.~abc();
Cout() << "after struct abc: "<< *a << EOL;
de d(a);
d.fecha();
d.~de();
Cout() << "after struct de: "<< *a << EOL;
}
|
|
|
Re: differences in returns between pointer and reference [message #56942 is a reply to message #56940] |
Sun, 02 May 2021 18:01 |
Oblivion
Messages: 1092 Registered: August 2007
|
Senior Contributor |
|
|
Hello BetoValle,
In the first instance you are copying the string to another string, not working on a reference.
struct abc{
String b;
public:
abc( String& xx){
b=xx; // <-- the xx variable will be copied to b;
}
void fecha(){
b="retornado"; // this not return: reference constructor is address (No, because you are not working on a reference. You are working on a local variable called "b", which will be destroyed with the struct, by the way.)
}
~abc(){}; // << - Will destroy b.
};
This will work:
struct abc{
String& b; // <-- Now b is a reference.
public:
abc( String& xx)
: b(xx) // > B will refer to xx;
{
}
void fecha(){
b="retornado"; // Will now set the referred object (xx).
}
~abc(){}; // << - Will not destroy what b refers to (xx).
};
[/code]
Best regards,
Oblivion
Github page: https://github.com/ismail-yilmaz
upp-components: https://github.com/ismail-yilmaz/upp-components
Bobcat the terminal emulator: https://github.com/ismail-yilmaz/Bobcat
[Updated on: Sun, 02 May 2021 18:15] Report message to a moderator
|
|
|
|
Goto Forum:
Current Time: Thu Apr 25 19:39:05 CEST 2024
Total time taken to generate the page: 0.06564 seconds
|