Edit: Thanks all. Lots of great info to go over. Will take me a while to absorb.
After 10+ years of an unhealthy romance with programming, I think I'm finally getting my head around pointers. But I'm still not comfortable with them.
I have some relatively simple code:
#include <iostream>
#include <string.h>
using namespace std;
class MyString
{
private:
char* buffer;
public:
//Constructor
MyString(const char* initString)
{
if(initString != NULL)
{
buffer = new char[strlen(initString)+1];
strcpy(buffer, initString);
}
else
buffer = NULL;
}
//Destructor
~MyString()
{
cout << "Invoking destructor, clearing up\n";
if (buffer != NULL)
delete [] buffer;
}
int GetLength()
{
return strlen(buffer);
}
const char* GetString()
{
return buffer;
}
};
int main()
{
MyString SayHello("Hello from String Class");
cout << "String buffer in MyString is " << SayHello.GetLength();
cout << " characters long\n";
cout << "Buffer contains: " << SayHello.GetString() << endl;
return 0;
}
Why does MyString
wish to make a pointer from the first argument (in main()
?) Why doesn't it just pass by copy? or use the address of operator?
Am I asking the 'wrong question'? Not seeing something clearly?
Many thanks. Hope the question is clear.