Assign List<B> object to List<A> object - list

I have a problem that I want to know if there is a magic trick or pattern to solve this in the other way.
I have list of B class objects, but I need to return list of A class objects. 'A' and 'B' classes have exactly the same fields (I need to return List, but I have List because it was mapped from database by hibernate) and I need to return it inside List of A objects because I can not import B class to other project (where class A is) beacuse of maven cyclic reference.
I just rewrote all fields from every object in for loop.
Is there any other way to solve this without doing it inside the loop?
Thanks in advance for discussion :)
Cheers! :)

Did you try returning Object type list? It could then be type-casted to B type .

In a perfect world you would extend both classes from one base class to make them copatible, but i see that this is not possible here.
in my opinion your approch is already the savest way to solve the problem.
another way would be to solve it over reflection. It's not recomendable - just pointing this out.
In this solution, you iterate over all declared fields of the given object, read out the value and set the field with the same name in your object to this value.
like i said, it's not recomendable because it relies on field names which may change.

Related

Is there a way to add a pre created class to a vector?

First off, I'm new to c++, currently learning it online.
I greatly appreciate any help...
I have a vector of classes set up for vehicles, however it should also contain derived classes for vehicles of different types (car, truck, van).
My class is set up to have functions to gather user input and assign that to different variables, I do not use the constructor for this. Is that wrong?
In my main this all works fine and dandy but when I go to add the class to the vector I run into issues, first off, My instructor informed us to use smart pointers for this, so I initialize my vector like so...
vector<unique_ptr<Vehicle>> vehicles;
This is how I'm adding classes to that vector...
// For base class...
vehicles.push_back(make_unique<Vehicle>());
// For derived class...
vehicles.emplace_back(make_unique<Car>());
This is where I am stuck, adding the class this way will cause it to be called and therefor the constructor called as well. What I would like to do is just add a class that I have already created and defined beforehand, for example..
// Functions to gather user input, validate and display...
Vehicle vehicle;
vehicle.getMake();
vehicle.validateName(vehicle.make);
vehicle.getModel();
vehicle.validateName(vehicle.model);
vehicle.displayVehicle();
vehicles.push_back(/* Somehow add 'vehicle' */);
Thanks for any help, I understand this might be the wrong way to do this, I was just struggling to find a solution and this is currently where I am at.
My class is set up to have functions to gather user input and assign that to different variables, I do not use the constructor for this. Is that wrong?
A constructor shouldn't do lots of things, and never prompt for user input… but, at the same time, it should not be possible to have a "half-ready" object at any point. I suggest you gather all your user input first, then pass it into the constructor so your object is ready to go in one step.
(I have not shown this in the following example.)
This is where I am stuck, adding the class this way will cause it to be called and therefor the constructor called as well. What I would like to do is just add a class that I have already created and defined beforehand, for example..
Your vector contains unique_ptr<Vehicle>s, so you'll want to start off with one:
std::unique_ptr<Vehicle> vehicle = std::make_unique<Vehicle>();
vehicle->getMake();
vehicle->validateName(vehicle->make);
vehicle->getModel();
vehicle->validateName(vehicle->model);
vehicle->displayVehicle();
vehicles.push_back(std::move(vehicle));
Notice that all the vehicle. are now vehicle->, because vehicle is no longer an actual Vehicle but instead a pointer to one.
std::move is needed because unique_ptrs are not copyable, only moveable.
Taking my advice from the start of the answer, this gets somewhat simpler:
std::string make = GetMake();
ValidateName(make);
std::string model = GetModel();
ValidateName(model);
vehicles.push_back(std::make_unique<Vehicle>(make, model));
vehicles.back()->displayVehicle();
I've moved the displayVehicle call to the end, because it shouldn't make a difference to your output, but allows us to do the "construct Vehicle" and "put it into vehicles" steps simultaneously.
This approach assumes that you have altered your constructor to take make and model, and set up free function GetMake(), GetModel() and ValidateName() to do those tasks.

Check if two instances of my class are equal using templates

I want to check if two instances of my class are equal(in C++), there are no pointers in the class. I understand that I would need to override the = operator and manually check all the fields. I am aware of that solution. The problem is that I have like around 100 members in the class, and I would want to do it for many classes of similar sizes.
My questions is if there is a way to templatize this? Is this possible? I am fine using velocity.
You can use a std::tuple. The obvious drawback is that you need to refer to your members by std::get<size_t>().

Creating a unique ID for class types C++

My goal here is to create a unique ID (starting a 0) for each child of a specific class. I'm not sure if it is possible in the way i want, but i figured i'd ask here as a last resort.
Some context:
I'm creating my own 2D game engine and i want it to have an ECS as it's back bone (Before anyone says anything, i'm doing this as a learning experience, i know i could just use an already existing game engine). My idea is that each class that implements the 'EntityComponent' class should have a unique ID applied to it. This needs to be per child, not per object. I want to use this ID as the index for an array to find the component of an entity. The actual ID that each Component gets is unimportant and each component does not need to be assigned the ID every run time.
My hope is there is some way to create something similar to a static variable per class (That implements the Entity Component class). It needs to be quick to get this value so doing an unordered_map lookup is slower than i would like. One thing i do not want to do is setting the ID for every component myself. This could cause problems once many components are made and could cause problems if i forget to set it or set two components to the same ID.
One idea i had was to make a variable in EntityComponent called ID (And a getter to get it). When the entity is constructed it looks up an unordered map (which was made at run time, assigning an ID to each class) for what ID it should have. The price of looking up once at construction is fine. The only problem i see with this is there is a lot of redundant data (Though overall it seems it would account to a pretty small amount). With this, every single transform component would have to store that it its ID is x. This means potentially thousands upon thousands of transform components are storing this ID value, when only 1 really needs to.
Basically i am after an extremely quick way to find an ID for a class TYPE. This can be through a lookup, but it needs to be a quick lookup. I would like something faster than unordered_map if possible. If this can be done through compile time tricks (Maybe enums?) or maybe even templates i would love to hear your ideas. I know premature optimisation is the bad, but being able to get a component fast is a pretty big thing.
What i'm asking might very well be impossible. Just thought i'd ask here to make sure first. I should also note i'm trying to avoid implementation of this in the children classes. I'd like to not have to set up the same code for each child class to create an id.
Thank you.
In order to get something corresponding to the actual type of an object, it either needs to be in the object itself or accessed via a virtual function. Otherwise the type will be determined by the type of the variable it is associated with.
A common option when speed and size are both important is to have an integer identifier associated with each type (when the full type list is known at compile time) and use that integer value in a specific way when you want to do something based on the type.
The integer mechanism usually uses an enum for generating the corresponding value for each type and has that field in every object.
The virtual method variety, I've used boost::uuid and a static data member in each class and a virtual method get'er for it.
Declare a virtual function newId() in EntityComponent.
Implement this function to get and increment a static variable in each class, which children you want to have a unique Id.
Assign Id in the constructor:
mId = newId();
don't know this if this is what you meant and i know this is an old post however this is how im currently dealing with a similar issue, maybe it will help someone else.
(Im also doing this as a learning experience for uni :) )
in the controlling class or its own utility class:
enum class EntityType{ TYPE_ONE = 0, TYPE_TWO =1};
in class header:
#include "EntityType.h"
class Whatever{
public:
inline void getType(){return _type;}
OR
inline void getType(){return EntityType::TYPE_ONE;}
private:
EntityType _type = EntityType::TYPE_ONE;
};
Hope this is helpful to anyone :)

multiple inheritance and polymorphism

my dizzyCreature class inherits from both a creature class and a dizzy class. It is also part of a polymorphic collection of creature classes. If I know that my object in the creature class is a dizzyCreature, is there a way to call a function from the dizzy class?
I have tried
creature[2].dizzyCreature::someFunction();
and
dizzyCreature::creature[2].someFunction();
and neither works. Any ideas?
If I understand correctly what you have is something like this: list<Creature*>. This list contains some dizzyCreature instances. On those instances you want to call methods of dizzy class. If this is the objective then you can use dynamic_cast to achieve this. Lets say you have Create* pCreature then you can do:
dizzyCreature* pDizzyCreature = dynamic_cast<dizzyCreature*>(pCreature);
if(pDizzyCreature )
{
pDizzyCreature->someDizzyClassMethod();
}
You need to first check if the class is of the correct type, then cast it using dynamic_cast, as has already been suggested. This solution is elegant since the dynamic cast itself does the type-checking - i.e. it will return NULL if you try to make an invalid cast. (There is no need to use typeid)
As a side note, if I were you, I'd attempt to do whatever it is you're trying to do without multiple inheritance if possible. Multiple inheritance can open up a whole can of worms and is best avoided unless there is no other alternative.

How to allow your data structure to take in objects of any class - C++

How do I do that? Like you know in Java, you can use an ArrayList and it will take any object as long as you cast it down to whatever it is when you're retrieving the object.
Even better, you can specify what class of objects that ArrayList would store by doing...
new ArrayList()< whateverObject >
I've implemented a linked list data structure in C++ and I'd like to know how I can allow it to do this...
At the moment, I'm just using...
typedef whateverObject ItemType
at the start of my header file for my linked list and then manipulating "ItemType" throughout the implementation of the linked list. So every time I want to change the type, e.g. instead of using the list for storing strings, I want to store an int, I'll have to change the typedef in my linked list's header but I want to be able to simply use it for any object so...
How?!
Thanks.
Templates are the answer to your question.
Define your linked list as follows :
template<typename ItemType>
class ArrayList
{
// What's inside your class definition does not need to be changed
// Include your method definitions here and you'll be fine
};
The type to use is then ArrayList<WhateverObject>.
Use templates. It's a lot to explain so I'll just give you a link where it's explained much better than I'll ever be able to do here: C++ FAQ - Templates.
While you're at it, if you have the time, I suggest you read the whole FAQ, it's really a great resource!
If I have understood well what you ask, templates is what you want.
Take a look here:
http://www.cplusplus.com/doc/tutorial/templates/
In java you can do so, because all classes are inherited from one base class Object. In C++ you do not have it. The reason is that Object base class impose overhead for all objects, while C++ do not like any unnecessary overhead.
If you want to store any object - you can store "void *" data type. The question remained - what you will be able to do with objects, without the knowledge of the type? If you do know - you can cast to the needed type and use it. The practice described above is not safe, and templates are better in most cases.