Hi there. Pointers confused me till the first day I used them (1 year ago) and still can't understand them 100%.

My problem is: I've read from a book that when you have
a class with a char* member you must create your own copy constructor,allocate memory dynamically...

but this works fine

#include <iostream>
using namespace std;

class Name
        {
         private:
                 char* fname;
         public :               
                 Name(char* k="no name"){fname=k;}
                 ~Name(){delete [] fname;}
              
                 void print(void) {cout<<fname<<endl;}
         };

int main()
{
    Name name("alex"),Obj(name);
    name.print();
    Obj.print();
    Obj.~Name();
    name.print();

getchar();
return 0;
}

unless I change constructor's body with

{fname=new char[strlen(k)+1];
              strcpy(fname,k);}

What is finally going on? How confusing pointers could be?

...but this works fine...

It shouldn't. Your first code sample should die a fiery death (and it does). It's because when you have code like this:

char* c;
c = "some string in memory";

you're just changing where the pointer c points to. It really points to some random place in memory. When you do something like

char* d;
d = new char[someLength];

you're allocating some specific memory, then pointing d at it. This has repercussions, since if you change the value of d you won't have a pointer to your allocated memory (unless of course, you've copied the address to another variable). In order to prevent your program from leaking the dynamically allocated memory, you have to delete it. Here's the tricky part - if you delete memory that wasn't dynamically allocated (like the first code segment), things go boom. That's the problem your code has.

As a side note, you should never call a destructor. It happens when the object goes out of scope or (if it's dynamically allocated) when it's deleted.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.