Cheating Strings

I've run into a few scenarios where I need to pass a string to an object. I had baulked at this as I didn't want to dynamically create a string (character array) as part of the object instatiation and then copy each character from the source string into the object's character array. In my anal-retentiveness I saw this as need for a string class which, again I would have to write from scratch. So as I said, this stumped me a couple of times.

Forgive my denseness, but I've just realised I can, in my class definition, store a character pointer (which can be passed in via a constructor) instead of a character array. Then whenever the object needs to print the string it uses the pointer to access the character array that (hopefully) is still in scope, but was defined outside the class.

So there's a big benefit in not having to manage strings beyond the simples declaration and passing a pointer. The down-side is the dependence on an external declaration and ensuring it's in scope whenever the object holding the pointer needs to use it.



Main sketch (.PDE) file:
#include "StringHolder.h"

void setup()
{
Serial.begin(115200);
Serial.println("setup()");
char name[] = "Christian Murphy";
StringHolder it(name);
it.printString();
}

void loop()
{
Serial.println("loop()");
delay(1000);
}



StringHolder.h file:
#ifndef StringHolder_h
#define StringHolder_h

#include "WProgram.h"

class StringHolder
{
public:
StringHolder(char* string);
void printString();
private:
char* _string;
};

#endif



StringHolder.cpp file:

#include "StringHolder.h"

StringHolder::StringHolder(char* string)
{
_string = string;
}

void StringHolder::printString()
{
Serial.println(_string);
}

That is all.

Comments