passing pointer THIS to copy constructor
Jun 27, 2011 at 1:56pm UTC
Hi guys, I am trying to make use of the copy constructor using the pointer this, but it gives me a segfault. Is it possible using the this pointer to create another object or am I making a terrible mistake here?
1 2 3 4
private :
char *titulo;
char **opc;
int nopc;
1 2 3
Menu Menu::operator +(char * nuevaopcion ) {
Menu tmp(*this ); //segmentation fault
}
1 2 3 4 5 6 7 8 9 10
Menu::Menu (const Menu &p1) {
this ->titulo=new char [strlen(p1.titulo)+1];
strcpy(this ->titulo, p1.titulo);
this ->nopc=p1.nopc;
for (int i=0; i<nopc; i++){
this ->opc[i]= new char [strlen(p1.opc[i])+1];
strcpy(this ->opc[i],p1.opc[i]);
}
cout << this ->titulo<< endl;
}
prueba=test+"hola" ;
Jun 27, 2011 at 2:14pm UTC
It seems that you missed opc = new char *[nopc];
in the constructor.
Jun 27, 2011 at 2:14pm UTC
First thing I notice: The parameter to operator+ must be const char* so it can be used with literals like "hola".
Second: Your operator+ doesn't return a Menu object; it doesn't return anything.
See if the above 2 do the trick for you.
Jun 27, 2011 at 2:17pm UTC
You're not allocating space for opc:
1 2 3 4
//...
this ->nopc=p1.nopc;
this ->opc = new char *[this ->nopc]; // <- you forgot this
//...
Also, you don't need to put 'this->' before all your members like that. It's implied.
Also, that can all be avoided if you use strings instead of char arrays.
Jun 27, 2011 at 2:27pm UTC
It does seem to be some of those, ill look more into it, thank you guys for your help ;)
Topic archived. No new replies allowed.