Originally posted by: Cogman
nkgreen, generally you shouldn't declare variables on the same line (For reasons just like this).
I prefer the char* a over the char *a. To me, I'm defining a pointer variable, so the * is naturally part of the name. If I put the * on the name, it just looks like I'm trying to dereference an uninitialized variable.
Originally posted by: Sc4freak
That's perfectly legal, though.
Base* ba = new Base[3];
ba[0] = Derived();
ba[1] = Derived();
ba[2] = Derived();
The derived objects you construct will be "sliced" down into Base objects - that is, their type converts from Derived to Base. What isn't legal is this:
Derived* da = static_cast<Derived*>(ba);
For obvious reasons.
Future languages should enforce this ......
My C++ isn't strong but it seems to me like that should work just fine? You're not allocating space on the stack for objects of that class, just pointers, which should be the same size regardless of what you're pointing to. Am I wrong?Gah, sorry, I explained it wrong. This is what I did.
Derived* array = new Derived[size];
Base* ba = array;
ba[7];
While that will compile fine, it is not correct. (at least with gcc)
My C++ isn't strong but it seems to me like that should work just fine? You're not allocating space on the stack for objects of that class, just pointers, which should be the same size regardless of what you're pointing to. Am I wrong?
If you cast the array to an array of Base, the compiler will perform those calculations using sizeof(Base) instead. If Derived is larger than Base, the resulting address will be incorrect.
Base** array = new Base*[10];
for (int i=0 ; i < 10 ; ++i) array[i] = new Derived;