Reputation: 165
I have a class:
class Kunde{
char *name;
char *ort;
int *alter;
double umsatz;
int transaktion;
int id=0;
int dummyAlter=20;
public:
static int anzahl;
Kunde(char* n=(char*)"Max Maier", char* o=(char*)"Köln", int *a=&dummyAlter);
Kunde(const Kunde &k);
~Kunde();
void buy(double u);
static int getAnzahl();
};
In my .cpp-File I have:
Kunde::Kunde(char* n, char* o, int *a)
{
name=n;
ort=o;
alter=a;
id=anzahl++;
umsatz=0;
transaktion=0;
};
and I want to write a copying constructor.
This is achieved by:
Kunde::Kunde(const Kunde &k)
{
int lenname=(int)strlen(k.name)+1;
name=new char[lenname];
memcpy(name, k.name, lenname);
int lenort=(int)strlen(k.ort)+1;
ort=new char[lenort];
memcpy(ort, k.ort, lenort);
alter=new int;
memcpy(alter, k.alter, sizeof(int));
id=k.id;
anzahl++;
umsatz=k.umsatz;
transaktion=k.transaktion;
}
The code compiles just fine but when I execute it, it produces an error where I use memcpy to copy the data from k.alter to alter.
Do you see what is wrong? I tried stfw and rtfm but it seems I'm too stupid to find anything concerning "pure" int*'s instead of int*-Arrays.
Thanks for your time.
Upvotes: 2
Views: 596
Reputation: 165
After some hints from you folks I finally found the problems.
char*
s directly (you see this in the constructor) and by that only achieved that I had pointers to my strings.Solution:
Kunde::Kunde(char* n, char* o, int a)
{
int lenname=(int)strlen(n)+1;
name=new char[lenname];
memcpy(name, n, lenname);
int lenort=(int)strlen(o)+1;
ort=new char[lenort];
memcpy(ort, o, lenort);
alter=new int;
*alter=a;
id=anzahl++;
umsatz=0;
transaktion=0;
}
int*
as a parameter for the constructor which a) makes no sense and b) is a royal PITA. After I fixed my parameters I used the construct proposed by @Matthias247 to do the copying of the int-data.Solution:
Kunde::Kunde(const Kunde &k)
{
int lenname=(int)strlen(k.name)+1;
name=new char[lenname];
memcpy(name, k.name, lenname);
int lenort=(int)strlen(k.ort)+1;
ort=new char[lenort];
memcpy(ort, k.ort, lenort);
alter=new int;
*alter = *(k.alter);
id=k.id;
anzahl++;
umsatz=k.umsatz;
transaktion=k.transaktion;
}
Upvotes: 1
Reputation: 409364
Regarding your problem with the integer pointer, your problem is twofold: First you have the default argument in the constructor which is a pointer to the address 20
, not a pointer to the value 20
. The second problem is that you use the address-of operator in the memcpy
call, it will give you the address of the pointer, i.e. you have an expression of type int **
.
Upvotes: 3