View Single Post
Old Oct 3rd, 2005, 9:25 PM   #2
Animatronic
Programmer
 
Join Date: Jun 2005
Posts: 99
Rep Power: 4 Animatronic is on a distinguished road
If you want the dog just to have a reference to the name and not take ownership of it ( not be able to change it ) do this:

class Dog
{
public:
	const char * Name;
};

Dog oneDog;
oneDog.Name = "Spot";
function( oneDog.Name );

void function( const char * name )
{
}

If you want the dog to own the name, so it can change it's name later do this:

#include <cstring>

class Dog
{
public:
	char Name[5];
};

Dog oneDog;
std::strncpy( oneDog.Name, "Dog", 5 );
function( oneDog.Name );

void function( char * name )		//if you want to change it
{
}
void function( const char * name )	//if you dont want to change it
{
}

There is an easier route however, as you are using C++ you can take advantage of the string class defined in the standard library. This is, by far, the prefered option:

#include <string>

class Dog
{
public:
	std::string Name;
};

Dog oneDog;
oneDog.Name = "Spot";
function( oneDog.Name );

void function( string & name )		//take a reference you can change
{
}
void function( const string & name )	//take a reference you can't change
{
}
void function( string name )			//create a copy of the name (slowest method)
{
}

The string class makes string operations much easier e.g. defining the == opertor to test if two strings are equal. See here for more examples.

edit: added in functions.

Last edited by Animatronic; Oct 3rd, 2005 at 9:36 PM.
Animatronic is offline   Reply With Quote