When passing an object to a function, a copy of the object is not created
FB
Type Person
public :
dim names as String
End Type
Declare Sub try_to_modify (p As Person)
Dim as person p
p.names = "A"
print "p.names = A", p.names
try_to_modify (p)
print "p.names = A?", p.names
sleep
end
Sub try_to_modify (p As Person)
p.names = "B" '/ only local object changes
print "func p", p.names
End Sub
+++++++++++++++++
Ci++
class Person {
public:
string name;
};
void try_to_modify (Person p)
{
p.name = "B"; // only the local object changes
}
int main ()
{
Person p;
p.name = "A";
try_to_modify (p);
cout << p.name; // "A"
}
According to the C ++ description, p.name is equal to A.
But in an FB program, the result will be:
p.names = A A
func p B
p.names = A? B
And I expected:
p.names = A A
func p B
p.names = A? A
Am I wrong somewhere or FB is different from Ci ++?
Please tell me what's the matter?
Inconsistency between FB and C ++ (no copy of the object is created)?
Re: Inconsistency between FB and C ++ (no copy of the object is created)?
FB by default passes most things ByRef. If you want the C++ result you need to pass it ByVal.
Code: Select all
declare sub try_to_modify(byval p as Person)
Sub try_to_modify (byval p As Person)
p.names = "B" '/ only local object changes
print "func p", p.names
End Sub
Re: Inconsistency between FB and C ++ (no copy of the object is created)?
that is, is this a feature of Freebasic?
Re: Inconsistency between FB and C ++ (no copy of the object is created)?
FB by default passes most things ByVal, except strings and arrays and UDT instances ByRef.Imortis wrote:FB by default passes most things ByRef. If you want the C++ result you need to pass it ByVal.
Re: Inconsistency between FB and C ++ (no copy of the object is created)?
Crap. You are correct. I always make that mistake. You would think I would remember it one of these days. Thanks for correcting my misinformation.
-
- Posts: 8586
- Joined: May 28, 2005 3:28
- Contact:
Re: Inconsistency between FB and C ++ (no copy of the object is created)?
@PavelUT independent of the use BYVAL or BYREF a FreeBASIC String (it's an UDT) isn't compatible with a C++ string (it's a class) !
(so far I know)
Joshy
(so far I know)
Joshy
Re: Inconsistency between FB and C ++ (no copy of the object is created)?
Correct. The strings you are using in C++ are of class std::string and they are not accessible from FB. There was a thread on this a while back where someone tried to make a .bi file to wrap stl::string but it turned out to be impossible given some differences between the FB and C++ object models. FB strings can be passed to C functions that are looking for a char * pointer to a null-terminated character array, however. The compiler automatically passes a pointer to the actual string data when you do that. Very convenient for C interoperability.