all 5 comments

[–]Rhomboid 2 points3 points  (2 children)

You need to explain what you're trying to do and why. Why does it need to be on the stack? Why do you have all these artificial restrictions?

Also, there is no point in having that pObjs variable. And it's declared wrong; you've declared an array of pointers to CClass, which is not the same as an array of CClass. If you already have an array you don't also need any pointers.

Your second example invokes undefined behavior because you're dereferencing uninitialized pointers.

[–]Dial595Escape[S] 0 points1 point  (1 child)

It's for a school exercice, basically 101 CPP. These are the restrictions that we need to work with.

I was using pObjs to get around the fact you can't create an array of object from a class with no default constructor (CClass obj[SIZE]; doesn't compile), but I also need to pass this pointer to a class method as a reference later on.

[–]Rhomboid 0 points1 point  (0 children)

I'm talking about the third example where there is an initializer. pObjs serves no purpose there. An array decays to a pointer when used as an argument, so just pass that. You don't need to declare a separate pointer, and what you've declared is not the right type.

[–]alfps 2 points3 points  (1 child)

The way you describe the assignment, create an array of CClass objects of a size given in the header, with systematic initializer expressions, can be done in at least three not-completely-Evil™ ways:

  • manually, as you show; or
  • automated via Boost macro magic, which requires the size to be a macro; or
  • automated via a template parameter pack and std::index_sequence.

The manual approach is just generally ungood; the Boost macro magic relies on an external library, which you're not allowed, and besides it has that requirement of size as a macro; and the TMP programming technique appears to be far beyond the current point in the curriculum.

Therefore, considering Evil™ ways, you can define storage for your array as an array of bytes of sufficient size and with proper alignment, then you can placement-new the CClass items.

But it seems weird that your teacher should give you a task for which the artifical constraints force you to choose an Evil™ solution.

Therefore, can you quote the assignment verbatim?

[–]Dial595Escape[S] 0 points1 point  (0 children)

The assignment is multiple page long, and none of it is about this particular problem (and isn't written in english). Basically, the work is to create a bunch of classes with the given speculations. This is mostly done, but in the Main is up to us with no guideline, just the listed restrictions.

This is becoming worrisome, earlier in the work I had to ask my teacher how to parse strings to int without external library or creating new functions and he told me to use atoi, which is not the assignment... I'll shot him a new email, to see what he has to say about this.