Reputation: 3
I'm kind of new in C++ classes and I need to make a copy constructor that uses pointers to object. My class looks like this:
class test
{
int a;
char *b;
public:
test()
{
a=0;
b="\0";
}
test(const test &p)
{
b=new char(strlen(p.b)+1);
b=p.b;
a=p.a;
cout<<"The copy constructor works";
}
void seta(int nr)
{
a=nr;
}
void setb(char *s)
{
b=s;
}
int geta()
{
return a;
}
char *getb()
{
return b;
}
};
Now I have a pointer to an object
test *x;
x=new test;
What I need to do is to create another pointer to object,*y,that will have the same values as x,using the copy constructor. If they were objects and not pointers,that copy constructor would have worked. Can you tell me what I should do,please? Thanks!
Upvotes: 0
Views: 85
Reputation: 20063
Simple, just dereference x
when you pass it to the constructor of test
.
test* y = new test(*x);
Upvotes: 0
Reputation: 254431
What you should probably do is not use pointers.
If you really want to do this, you can combine new
with a copy-constructor thusly:
test *y = new test(*x);
You also need to fix your copy constructor to copy the contents of the string, not the pointer:
strcpy(b, p.b); // not b = p.b;
and fix the default constructor so it doesn't point to a string literal (which will fail to compile on a modern compiler, and will go horribly wrong if you ever try to add a destructor to fix the memory leak).
If you're new to C++, you might have more fun using basic types, and friendly library types like std::string
, before facing the insanity of pointers and memory allocation.
Upvotes: 2