I dont know why, but I have declared a friend external function called hello of class proof and when the function is executed, the program crash...the program gives me the solution but later It crashs...any help?
#include <iostream>
#include <cstring>
using namespace std;
class proof{
public:
//constructores
proof(int a2,int b2) : a(a2), b(b2), pa(&a2),pb(&b2) {}
proof():a(0),b(0){}
proof(int *pa2,int *pb2,int a2,int b2) : a(a2),b(b2),pa(&a2),pb(&b2){}
~proof (){ //destructor, borra los punteros cnd sale del ambito de la clase.
delete pa;
delete pb;
}
//declaracion de funciones
void screen(int *pa2,int *pb2,int a2,int b2);
void screen(int a2,int b2);
void screen();
void recognise(proof &a2);
private:
int a,b;
int *pa,*pb;
friend void hello(proof);
};
//funciones de la clase
void proof::screen(int a2,int b2){
Rule of Three: if you need a custom destructor, copy constructor of assignment operator, you probably need the three.
in the function `hello()' you are passing the parameter by copy,
the copy constructor provided by the compiler will perform a shallow copy of the object, that means that `a2.pa' and `second.pa' point to the same memory address.
When the `hello()' function ends, `a2' is destroyed and the `a2.pa' pointer is deleted.
then `main()' ends and attempts to destroy `second', so you've got a double delete.
> proof pointer(&a,&b,15,25);
`pa' would point to memory that was not allocated with new
I have fixed the trouble, changing my constructor proof():a(0),b(0){}form this to proof():a(0),b(0),pa(0),pb(0){}.
In that way, I assign valoures cero to both pointers, but my programm crashed from a call with an object made with a different constructor...this one
proof(int a2,int b2) : a(a2), b(b2), pa(&a2),pb(&b2) {} which has all the members assigned.
I havent understood so weel your answer ne555, I know It's a trouble of concept that I dont know or I cant still manage well...what you mean is that when a function finishs his task it deletes their temporary object( because it was called by copy not by reference) adn when main finishs It calls the destructor whcich try to delete again the same??