Subclass objects in one array?
Hi
i want to save similar objects, meaning having same superclass, in an array. Example: I have a superclass vehicle. Class car and truck inherit from vehicle. Now i have a few from both of them an want to put them in an array, vector, set or else. Is this possible in C++ or are there an workarounds? When i remember right, Java and C# offer this feature.
Here again an example:
Code:
class vehicle{
int mMaxSpeed;
}
class truck : public vehicle{
int mTrailerLength;
}
class car : public vehicle{
bool mHasHitch;
}
main()
{
truck mytruck = new truck();
car mycar = new car();
vector<vehicle> myCarPool;
myCarPool.pushback(mytruck);
myCarPool.pushback(mycar);
}
Greets
Re: Subclass objects in one array?
You can't store objects of different classes into a vector but you can store a base pointer. To avoid having memory leaks due to forgotten deletes you can make the vector store a smart pointer like boost::shared_ptr http://www.boost.org/doc/libs/1_50_0...shared_ptr.htm or std::shared_ptr if your compiler supports them. http://en.cppreference.com/w/cpp/memory/shared_ptr
Re: Subclass objects in one array?
... Besides, your "syntax" for new and main() looks like to be incorrect. Did you probably mean:
Code:
int main()
{
truck* mytruck = new truck();
car* mycar = new car();
vector<vehicle*> myCarPool;
myCarPool.pushback(mytruck);
myCarPool.pushback(mycar);
...
delete mycar ;
delete mytruck;
return 0;
}
:confused:
Re: Subclass objects in one array?
Quote:
Originally Posted by
ImNotaBot
Here again an example:
Note that the vehicle class must have a virtual destructor if you want to store (and ultimately delete, I presume) derived instances using a pointer to the base class.
You can also have a look at the Boost Pointer Container Library.
Re: Subclass objects in one array?
Quote:
When i remember right, Java and C# offer this feature.
The method that Java and C# use is similar, under the hood, to what you do in C++.
There is not actually much difference between the concepts of Java & C++.
Both have containers that store one type of object.
In Java, you can only store references to objects in a container.
In C++ you store copies of objects in a container. The difference being that is that the objects stored could be pointers.
Code:
vector<car> myCars; // A vector of 'car' objects. The 'car's are stored in the vector. No equivalent in java.
vector<car *> myPointerCars; // A vector of pointers to 'car' objects. The 'car's are stored elsewhere.
Re: Subclass objects in one array?
Well sorry that I did not answer. Quite impolite... but I am terribly under pressure of time due to exams.
I will come back to the topic as soon as i made them.
I really appreciate your help so thanks to all of you.
@ VictorN: Yes your right :-D i just wrote it down for a quick sloppy illustration of the problem.