el_rooky
asked on
string class argument
I've got a very simple and dumb question. When I pass a string class as an argument to a function as in the code belowed, I am passing a pointer or am I creating a copy of myStr in foo?
#include <string>
#include <iostream>
#include <stdlib.h>
using namespace std;
string myStr = "this is my string";
foo(myStr);
...
//------------------------ -------
void foo(string s);
{
}
#include <string>
#include <iostream>
#include <stdlib.h>
using namespace std;
string myStr = "this is my string";
foo(myStr);
...
//------------------------
void foo(string s);
{
}
you are creating a copy of myStr. Its passed by value
I meant constructor of the string class is called and then its passed.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
khkremer,
Thanks for you answer. One more small question. When you say pass as a pointer you don't mean a pointer to the string class.
For example, can I have a pointer to the string class like this?
string *ptr = myStr;
Thanks for you answer. One more small question. When you say pass as a pointer you don't mean a pointer to the string class.
For example, can I have a pointer to the string class like this?
string *ptr = myStr;
Yes, you can do this, but this will require that you modify how you work with the string (the first part of your sample code is correct, the second part is not):
string * ptr; // this only defines a pointer to a string, not the string itself
ptr = new string(myStr); // this creates the new string object and uses the content of myStr as it's value
// ... do something with the string ...
delete ptr; // destroy the object and deallocate any resources (e.g. memory)
You can also use something like this:
string * ptr;
*ptr = myStr; // copy the contents of myStr to *ptr (which dereferences the pointer, and therefore is a string)
// ...
delete ptr;
string * ptr; // this only defines a pointer to a string, not the string itself
ptr = new string(myStr); // this creates the new string object and uses the content of myStr as it's value
// ... do something with the string ...
delete ptr; // destroy the object and deallocate any resources (e.g. memory)
You can also use something like this:
string * ptr;
*ptr = myStr; // copy the contents of myStr to *ptr (which dereferences the pointer, and therefore is a string)
// ...
delete ptr;