I can see this is related to your previous topic. Please don't create a new topic about the same subject, it's ultimately a time waster for those who reply: the same things are said in both topics.
Did you take on board
MikeyBoy's last post in the other topic?
The idea is that now, my class Material Point iheritate the protected data members of particle and position. |
As
MikeyBoy pointed out you should use composition here, not inheritance. Further to that, there are 3 relationship types:
1. "IS A" A Toyota IS A car, implies public inheritance;
2. "HAS A" A car HAS wheels, implies composition, the Wheel type is a member of Car.
3. "USES A" A Car can tow a ("USES A") trailer. The Trailer type is an argument to a function that involves Car.
int Car::ConnectTrailer(const Trailer& MyTrailer);
using
new
is bad because if an exception is thrown, the destructor is never called and memory is leaked.
The best thing to do is use an STL container like std::vector for example, it stores it's data on the heap and takes care of memory management for you. Doing memory management yourself is error prone.
Having
protected
data is bad because if one has to change anything it could break code. Keep data
private
, and have a getter function to retrieve it. The fact that you have a function now means that you can alter the internals of the function without breaking the code that calls that function. Note, lots of people think OOP is easy: there are related functions & data in a class. But that is not the case, there is quite a lot to learn to do OOP properly.
Storing data on the stack is fast, but limited in size, on my Linux system it is only 8MB. Storing on the heap is slower, because the memory allocation is a slow heavy function. But it is not so bad if one allocates all the memory at once. STL containers like
std::vector
have functions such as
reserve()
which will allocate in one step. So if one had 1 million items in a vector, that could all be allocated at once with a call to the reserve function.
As you have proved to yourself, ordinary pointers work with polymorphism, without using
new
. The runtime aspect of polymorphism works via a vtable (virtual table). As far as I understand it, it is a table of pointers which allows the compiler to check that a pointer or reference is a derived class of a base class, and ultimately allows the correct virtual function to be called.