I'm working on an assignment that uses OMNeT++, Veins/Sumo. Although my question is not completely related to it, it might add some context.
I'm familiar with programming, but having a little bit of trouble wrapping my head around the whole
The idea is that there is a network of cars, and all these cars are talking to eachother using messages. A message inlcudes the vehicle name, but also information about the current position/mobility of the car. This is where TraCIMobilitycomes in.
Ideally I would like to have all this information stored in the original class in the message, but I am running into some issues.
pointer/memory address idea when working with classes.
class InterVehicleMessage : public ::veins::DemoSafetyMessage
{
protected:
::omnetpp::opp_string vehicleName;
veins::TraCIMobility vehicle_mobility; <--- important
private:
void copy(const InterVehicleMessage& other);
protected:
bool operator==(const InterVehicleMessage&);
public:
//stuff
virtual veins::TraCIMobility& getMobility(); <--- important
virtual const veins::TraCIMobility& getMobility() const {return const_cast<InterVehicleMessage*>(this)->getMobility();} <--- important
virtual void setMobility(const veins::TraCIMobility& vehicle_mobility); <--- important
};
This all looks fine and dandy, I assume it functions as intended aswell.
But then when I try to make define the setMobility class I run into some problems.
void InterVehicleMessage::SetMobility(const veins::TraCIMobility& vehicle_mobility)
{
this->vehicle_mobility = vehicle_mobility;
}
This results in the error:
InterVehicleMessage_m.cc:240:28: error: object of type 'veins::TraCIMobility' cannot be assigned because its copy assignment operator is implicitly deleted
I'm not familiar with C++ enough to really know what this means. Is there anyone who could hint me into the right direction?
pastebin to TraCIMobility.h: https://pastebin.com/pGZEepxX
I've decided to save the information necesarry from TraCIMobility in individual variables.
So:
double speed;
veins::Coord position;
veins::Heading direction;
veins::Coord nextPositions[7];
Instead of:
veins::TraCIMobility vehicle_mobility;
As #PaulSanders stated in the comment, this class is not supposed to be copied.
Thanks everyone for their time and effort. Have a nice day.
Related
i'm creating particle system and i want to have possibility to choose what kind of object will be showing on the screen (like simply pixels, or circle shapes). I have one class in which all parameters are stored (ParticleSettings), but without those entities that stores points, or circle shapes, etc. I thought that i may create pure virtual class (ParticlesInterface) as a base class, and its derived classes like ParticlesVertex, or ParticlesCircles for storing those drawable objects. It is something like that:
class ParticlesInterface
{
protected:
std::vector<ParticleSettings> m_particleAttributes;
public:
ParticlesInterface(long int amount = 100, sf::Vector2f position = { 0.0,0.0 });
const std::vector<ParticleSettings>& getParticleAttributes() { return m_particleAttributes; }
...
}
and :
class ParticlesVertex : public ParticlesInterface
{
private:
std::vector<sf::Vertex> m_particleVertex;
public:
ParticlesVertex(long int amount = 100, sf::Vector2f position = { 0.0,0.0 });
std::vector<sf::Vertex>& getParticleVertex() { return m_particleVertex; }
...
}
So... I know that i do not have access to getParticleVertex() method by using polimorphism. And I really want to have that access. I want to ask if there is any better solution for that. I have really bad times with decide how to connect all that together. I mean i was thinking also about using template classes but i need it to be dynamic binding not static. I thought that this idea of polimorphism will be okay, but i'm really need to have access to that method in that option. Can you please help me how it should be done? I want to know what is the best approach here, and also if there is any good answer to that problem i have if i decide to make that this way that i show you above.
From the sounds of it, the ParticlesInterface abstract class doesn't just have a virtual getParticleVertex because that doesn't make sense in general, only for the specific type ParticlesVertex, or maybe a group of related types.
The recommended approach here is: Any time you need code that does different things depending on the actual concrete type, make those "different things" a virtual function in the interface.
So starting from:
void GraphicsDriver::drawUpdate(ParticlesInterface &particles) {
if (auto* vparticles = dynamic_cast<ParticlesVertex*>(&particles)) {
for (sf::Vertex v : vparticles->getParticleVertex()) {
draw_one_vertex(v, getCanvas());
}
} else if (auto* cparticles = dynamic_cast<ParticlesCircle*>(&particles)) {
for (CircleWidget& c : cparticles->getParticleCircles()) {
draw_one_circle(c, getCanvas());
}
}
// else ... ?
}
(CircleWidget is made up. I'm not familiar with sf, but that's not the point here.)
Since getParticleVertex doesn't make sense for every kind of ParticleInterface, any code that would use it from the interface will necessarily have some sort of if-like check, and a dynamic_cast to get the actual data. The drawUpdate above also isn't extensible if more types are ever needed. Even if there's a generic else which "should" handle everything else, the fact one type needed something custom hints that some other future type or a change to an existing type might want its own custom behavior at that point too. Instead, change from a thing code does with the interface to a thing the interface can be asked to do:
class ParticlesInterface {
// ...
public:
virtual void drawUpdate(CanvasWidget& canvas) = 0;
// ...
};
class ParticlesVertex {
// ...
void drawUpdate(CanvasWidget& canvas) override;
// ...
};
class ParticlesCircle {
// ...
void drawUpdate(CanvasWidget& canvas) override;
// ...
};
Now the particles classes are more "alive" - they actively do things, rather than just being acted on.
For another example, say you find ParticlesCircle, but not ParticlesVertex, needs to make some member data updates whenever the coordinates are changed. You could add a virtual void coordChangeCB() {} to ParticlesInterface and call it after each motion model tick or whenever. With the {} empty definition in the interface class, any class like ParticlesVertex that doesn't care about that callback doesn't need to override it.
Do try to keep the interface's virtual functions simple in intent, following the Single Responsibility Principle. If you can't write in a sentence or two what the purpose or expected behavior of the function is in general, it might be too complicated, and maybe it could more easily be thought of in smaller steps. Or if you find the virtual overrides in multiple classes have similar patterns, maybe some smaller pieces within those implementations could be meaningful virtual functions; and the larger function might or might not stay virtual, depending on whether what remains can be considered really universal for the interface.
(Programming best practices are advice, backed by good reasons, but not absolute laws: I'm not going to say "NEVER use dynamic_cast". Sometimes for various reasons it can make sense to break the rules.)
This is probably very basic but somehow I cannot figure it out.
Say I have a class A which embeds 42 Things, plus some common data:
class A {
Thing things[42];
int common_data[1024];
}
I would like each thing to have access to the common data, but I don't want to copy the data in each Thing object, nor pay the price of a pointer to it in each thing. In other word, I would like Thing to look like this:
class Thing {
int ident;
int f() {
return common_data[ident];
}
}
Of course here common_data is unbound. What is the canonical way to make this work?
FWIW I am working with a subset of C++ with no dynamic allocation (no "new", no inheritance, basically it's C with the nice syntax to call methods and declare objects); I am ideally looking for a solution that fits in this subset.
You can solve your issue by making the common_data attribute of Class A static. Static variables are shared by all members of class A, and will be accessible if you make it public.
class A
{
private:
Thing things[42];
public:
static int common_data[1024];
}
It can be accessed by doing...
A::common_data[index];
I am not sure if I understand the question correctly, but maybe this helps:
struct A {
Thing things[42];
int common_data[1024];
void foo(int index) {
things[index].doSomeThingWithCommonData(int* common_data);
}
};
struct Thing {
void doSomeThinWithCommonData(int* common_data) {
/* now you have access to common_data */
}
};
Your reasons for avoiding pointers/reference is based on irrational fears. "Copying" a pointer 42 times is nothing (read this word carefully) for the machine. Moreover this is definitely not the bottleneck of the application.
So the idiomatic way is to simply use dependency injection, which is indeed a slightly more costly action for you (if passing an array can be considered costly), but allows for a much more decoupled design.
This is therefore the solution I recommend:
struct Thing {
using data = std::shared_ptr<std::array<int, 1024>>;
data common_data;
Thing(data arg)
: common_data(arg)
{}
// ...
};
If the system is costrained, then you should benchmark your program. I can tell you already with almost absolutely certainty that the bottleneck won't be the copying of those 42 pointers.
I'm designing a chess game (C++ beginner) however I'm stuck on my checking process for individual piece types, eg pawn moving only 1 space at a time, except the first time moving 2 spaces, and so on.
I have a piece class, and a subclass of that is pawn, king, etc, which contains the method:
check(string position,string destination);
and return a boolean value whether it is possible to move to the destination.
I have a pointer to each piece which I have defined by doing:
pawn pawnPieces[16];
piece *pointer[16];
for (i=0;i<16;i++)
{
pointer[i]=&pawnPieces[i];
}
After my initial checking, I want to call the check function above from main, as a test:
cout << pointer[1]->check("B1","C1") << endl;
This gives me the error "no member named 'check' in piece" which makes sense, however I'm sure there would be a way to link the piece class to the pawn, king etc.
I think I need to do something with virtual functions from what I have read, but I am not sure how to approach this. If anyone could offer a few pointers that would be much appreciated.
This approach of trying to call the subclass function from a pointer to the class above it may be fundamentally flawed, perhaps I need to modify my design to achieve this goal? I still want to keep the check method of the pawn class in the same position, as I believe it encapsulates it well.
EDIT: I made a pure virtual function in the piece class:
virtual bool check(string positionIN,string destination)=0;
Now when I call the cout line above, I get a segmentation fault and I'm unsure why. I'm assuming it's because I'm using pointers?
EDIT2: Thank you for that! I have implemented this however I got a small error, is virtual meant to be attached to the pawn and king class? From my understanding I thought the virtual tag only goes on the base class.
EDIT3: I understand, I tagged the check function in classes pawn and king with the virtual tag and it compiled.
Now I am getting a segmentation fault through calling the object itself
pawnPieces[1].check("B1","C1")
and by calling the pointer to the object
pointer[1]->check("B1","C1")
from main, and I am not sure why.
EDIT4: All working now, I was calling it from main to test, however when I called it from within my program everything worked, thank you all!
What you are attempting to do is exactly what virtual methods are meant for.
class piece
{
public:
virtual bool check(string position, string destination) = 0;
};
class pawn : public piece
{
public:
virtual bool check(string position, string destination)
{
return ...;
}
};
class king : public piece
{
public:
virtual bool check(string position, string destination)
{
return ...;
}
};
I've been doing an exercise for my programming course and the particular one I'm on now is about friend functions/methods/classes. The problem I'm having is that my friend function doesn't seem to be doing it's job; I'm getting "[variable name] is private within this context" errors around my code where I'm trying to access the variables that the friend function should have access to.
Here is the class definition in the header file (I cut out unnecessary stuff to save space).
class Statistics {
private: // The personal data.
PersonalData person;
public:
Statistics();
Statistics(float weightKG, float heightM, char gender);
Statistics(PersonalData person);
virtual ~Statistics();
...
friend bool equalFunctionFriend(Statistics statOne, Statistics statTwo);
friend string trueOrFalseFriend(bool value);
};
Here is the method where the errors are appearing.
bool equalFuntionFriend(Statistics statOne, Statistics statTwo)
{
// Check the height.
if (statOne.person.heightM != statTwo.person.heightM)
return false;
// Check the weight.
if (statOne.person.weightKG != statTwo.person.weightKG)
return false;
// Check the gender.
if (statOne.person.gender != statTwo.person.gender)
return false;
// If the function hasn't returned false til now then all is well.
return true;
}
So, my question is: What am I doing wrong?
EDIT: Problem has been solved by Angew. Seems it was just a typo... Very silly me!
I'm guessing that heightM, weightKG and gender are private to your PersonalData class and this is why you're getting the error. Just because your functions are friends of Statistics, doesn't mean they have access to the internals of the members of Statistics. They only have access to the internals of Statistics. In fact, Statistics itself doesn't even have access to the internals of PersonalData, so its friends certainly don't.
There are a few ways around this. You could make the members of PersonalData public - but that's not a great idea because you will decrease encapsulation. You could make your functions also friends of PersonalData - you might end up with a strange graph of friendships (like Facebook for C++ classes!). Or you could give PersonalData some public interface that allows others to peek at its private data.
As #Angew pointed out in the comments, your function is named equalFuntionFriend when the friend of Statistics is named equalFunctionFriend - you have a missing letter. That would also cause this problem.
I have a C background and am a newb on C++. I have a basic design question. I have a class (I'll call it "chef" b/c the problem I have seems very analogous to this, both in terms of complexity and issues) that basically works like this
class chef
{
public:
void prep();
void cook();
void plate();
private:
char name;
char dish_responsible_for;
int shift_working;
etc...
}
in pseudo code, this gets implemented along the lines of:
int main{
chef my_chef;
kitchen_class kitchen;
for (day=0; day < 365; day++)
{
kitchen.opens();
....
my_chef.prep();
my_chef.cook();
my_chef.plate();
....
kitchen.closes();
}
}
The chef class here seems to be a monster class, and has the potential of becoming one. chef also seems to violate the single responsibility principle, so instead we should have something like:
class employee
{
protected:
char name;
int shift_working;
}
class kitchen_worker : employee
{
protected:
dish_responsible_for;
}
class cook_food : kitchen_worker
{
public:
void cook();
etc...
}
class prep_food : kitchen_worker
{
public:
void prep();
etc...
}
and
class plater : kitchen_worker
{
public:
void plate();
}
etc...
I'm admittedly still struggling with how to implement it at run time so that, if for example plater (or "chef in his capacity as plater") decides to go home midway through dinner service, then the chef has to work a new shift.
This seems to be related to a broader question I have that if the same person invariably does the prepping, cooking and plating in this example, what is the real practical advantage of having this hierarchy of classes to model what a single chef does? I guess that runs into the "fear of adding classes" thing, but at the same time, right now or in the foreseeable future I don't think maintaining the chef class in its entirety is terribly cumbersome. I also think that it's in a very real sense easier for a naive reader of the code to see the three different methods in the chef object and move on.
I understand it might threaten to become unwieldy when/if we add methods like "cut_onions()", "cut_carrots()", etc..., perhaps each with their own data, but it seems those can be dealt with by having making the prep() function, say, more modular. Moreover, it seems that the SRP taken to its logical conclusion would create a class "onion_cutters" "carrot_cutters" etc... and I still have a hard time seeing the value of that, given that somehow the program has to make sure that the same employee cuts the onions and the carrots which helps with keeping the state variable the same across methods (e.g., if the employee cuts his finger cutting onions he is no longer eligible to cut carrots), whereas in the monster object chef class it seems that all that gets taken care of.
Of course, I understand that this then becomes less about having a meaningful "object oriented design", but it seems to me that if we have to have separate objects for each of the chef's tasks (which seems unnatural, given that the same person is doing all three function) then that seems to prioritize software design over the conceptual model. I feel an object oriented design is helpful here if we want to have, say, "meat_chef" "sous_chef" "three_star_chef" that are likely different people. Moreover, related to the runtime problem is that there is an overhead in complexity it seems, under the strict application of the single responsibility principle, that has to make sure the underlying data that make up the base class employee get changed and that this change is reflected in subsequent time steps.
I'm therefore rather tempted to leave it more or less as is. If somebody could clarify why this would be a bad idea (and if you have suggestions on how best to proceed) I'd be most obliged.
To avoid abusing class heirarchies now and in future, you should really only use it when an is relationship is present. As yourself, "is cook_food a kitchen_worker". It obviously doesn't make sense in real life, and doesn't in code either. "cook_food" is an action, so it might make sense to create an action class, and subclass that instead.
Having a new class just to add new methods like cook() and prep() isn't really an improvement on the original problem anyway - since all you've done is wrapped the method inside a class. What you really wanted was to make an abstraction to do any of these actions - so back to the action class.
class action {
public:
virtual void perform_action()=0;
}
class cook_food : public action {
public:
virtual void perform_action() {
//do cooking;
}
}
A chef can then be given a list of actions to perform in the order you specify. Say for example, a queue.
class chef {
...
perform_actions(queue<action>& actions) {
for (action &a : actions) {
a.perform_action();
}
}
...
}
This is more commonly known as the Strategy Pattern. It promotes the open/closed principle, by allowing you to add new actions without modifying your existing classes.
An alternative approach you could use is a Template Method, where you specify a sequence of abstract steps, and use subclasses to implement the specific behaviour for each one.
class dish_maker {
protected:
virtual void prep() = 0;
virtual void cook() = 0;
virtual void plate() = 0;
public:
void make_dish() {
prep();
cook();
plate();
}
}
class onion_soup_dish_maker : public dish_maker {
protected:
virtual void prep() { ... }
virtual void cook() { ... }
virtual void plate() { ... }
}
Another closely related pattern which might be suitable for this is the Builder Pattern
These patterns can also reduce of the Sequential Coupling anti-pattern, as it's all too easy to forget to call some methods, or call them in the right order, particularly if you're doing it multiple times. You could also consider putting your kitchen.opens() and closes() into a similar template method, than you don't need to worry about closes() being called.
On creating individual classes for onion_cutter and carrot_cutter, this isn't really the logical conclusion of the SRP, but in fact a violation of it - because you're making classes which are responsible for cutting, and holding some information about what they're cutting. Both cutting onions and carrots can be abstracted into a single cutting action - and you can specify which object to cut, and add a redirection to each individual class if you need specific code for each object.
One step would be to create an abstraction to say something is cuttable. The is relationship for subclassing is candidate, since a carrot is cuttable.
class cuttable {
public:
virtual void cut()=0;
}
class carrot : public cuttable {
public:
virtual void cut() {
//specific code for cutting a carrot;
}
}
The cutting action can take a cuttable object and perform any common cutting action that's applicable to all cuttables, and can also apply the specific cut behaviour of each object.
class cutting_action : public action {
private:
cuttable* object;
public:
cutting_action(cuttable* obj) : object(obj) { }
virtual void perform_action() {
//common cutting code
object->cut(); //specific cutting code
}
}