I have doubt regarding copy constructor for a char* data member.
I have my code as,
#include<iostream>
using namespace std;
class Test
{
    char *str;
    int length;
public:
    Test(){}
    Test(char *a)
    {
        length = strlen(a)+1;
        str = new char(length);
        str = strncpy(str,a,length);
    }
    Test(const Test &t)
    {
        length = t.length;
        if(t.str)
        {
            str = new char(length);
            str = strncpy(str,t.str,length);
        }
        else
        str = 0;
    }
    void out(){cout<<str;}
};
int main()
{
    Test t("Test");
    Test t1 = t;
    t1.out();
    return 0;
}
In case of constructor and copy constructor instead of using strncpy to copy the data member value, if I use:
Test(char *a)
{
    str = new char();
    str = a;
}
Test(const Test &t)
{
    if(t.str)
    {
        str = new char();
        str = t.str;
    }
    else
    str = 0;
}
Will this also work? If yes, which method is preferable?
 
     
     
     
    