Hi all! I'm trying to implement a vector class in C + +. However when I go to actually run the main, it generates an interrupt operating system. Do you see a mistake? Thank you!
#include "header.h"
int main()
{
// Definisco le istanze delle classi
vettore <int> vet;
vettore <int> vet2;
vettore <int> vet3;
// SEZIONE VETTORI
// Leggo i valori delle varie istanze
vet.leggi_vettore();
vet2.leggi_vettore();
// Svolgo operazioni sulle classi
int scel;
cout<<"\nInserire:\n1 per la somma.\n2 per l'assegnazione.\nScelta: ";
cin>>scel;
switch(scel)
{
case 1:
vet3 = vet+vet2;
cout<<"\nIl risultato e': \n";
vet3.stampa_vettore();
break;
case 2:
//Faccio la verifica dell'assegnazione
vet=vet2;
vet2=vet2+vet;
// Stampo vet e vet2 e devono essere diversi.
vet.stampa_vettore();
vet2.stampa_vettore();
break;
default:
cout<<"\nSCELTA ERRATA!!!\n";
}
return 0;
}
Compile errors: elem = new T[]; illegal vet2=vet2+vet; `operator+' returns a temporary, but `operator=' requires a non-constant reference (you need to observe const correctness)
Logic errors:
_ Destructor should delete[] elem;
_ `vettore(int size)' creates a local `elem' variable (leaks memory and fails to initialize members)
_ `leggi_vettore()' access out of bounds.
_ `operator=' leaks memory and fails with self-assignment
You are right. As regards the second compile error was my oversight. Can you tell me instead of a correct solution to the first compile error? Thanks and sorry but it's a while that I program in C + + and start over is hard!
You might want to search on other threads to find other tips about that concept. Alternatively, why don't you just initialize the pointer to zero instead of allocating an array of 0? It should be safe since your functions check the value of n before trying to access elements. Just double check that the zero initialized pointer will never be used in other functions if the caller forgets to allocate before using some of the functions.
Your assignment operator will leak memory in some cases. You aren't checking to see if existing array needs to be deallocated before creating the new one. That's unrelated to the crash, but is just another observation.