Here is my problem :
I have 2 classes in my program. The first one builds an object A with 4 members variables. The second one builds dynamically an object B which is an array of a certain number of objects A. I wrote all the functions and overloads necessary.
In my main program, I create an object B and I want to write it with "cin", at the moment when I must inform the first variable member of the first object A of the object B, the program crashes. It says Something like "Access violation".
As I suspected the pointer was initialised to NULL, then attempted to use as though it was an array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
istream& operator >> (istream& is, CBouquet& B)
{
cout << "Veuillez composer votre bouquet :" << endl;
cout << "Indiquez le nombre de fleur(s) composant le bouquet :" << endl;
is >> B.N;
if (B.Bouquet)
delete[] B.Bouquet;
B.Bouquet = new CFleur[B.N];
cout << "Ajouter y maintenant les fleurs :" << endl;
for (int i = 0; i < B.N; i++)
{
is >> B.Bouquet[i];
}
return is;
}
Note I added line 10 which solved the problem, and lines 7 and 8 to avoid any memory leak.
Regarding void main(). That is not standard C++. Yes, some compilers will allow it, but others do not. Mine gave this error output and refused to compile at all:
3 11 main.cpp [Error] '::main' must return 'int'
28 Makefile.win recipe for target 'main.o' failed
It is best to start with good habits when learning, then your code should always work in any compiler (provided the compiler conforms to standards for C++).
I'd say any time your code modifies the value of N, you should be checking that the pointer Bouquet is also modified so it stores the same number of elements. Most of your existing code already does that - though I didn't test all of it or verify whether or not it is correct.
At line 5 you allocate space for objects 0 to Nf. At line 11 you set object Nf+1, which is out of bounds. My advice is to use Nf or Ct.Nf consistently though the function.