How would you structure the class interactions in a physics engine? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm writing a physics engine in C++ and I've come to a stop, namely how I should design the class hierarchy. What I'm specifically concerned about is the World and Body classes. Body should expose some details to World that World then can work on. But at the same time, I don't want users to be able to access all of those properties of Body. But I still want users of the engine to be able to change some things in a body. For example, its position. How would you structure this in terms of classes?

Define an interface (i.e. a pure virtual class) that specifies what functions you want exposed from Body. Have Body implement that inteface.
Allow that interface, and not Body to be used from World.
This pattern is called composition.

Recently, I've solved a similar problem by introducing a special interface for the restricted operations, and inheriting protectedly from it. Like this:
struct RestrictedBodyFunctions
{
virtual void step() = 0;
virtual Body& asBody() = 0;
};
struct Body : protected RestrictedBodyFunctions
{
static std::unique_ptr<Body> createInWord(World &world)
{
auto Body = std::unique_ptr<Body>{new Body()};
world.addBody(*body); // cast happens inside Body, it's accessible
return std::move(body);
}
std::string getName() const;
void setName(std::string name);
protected:
void step() override
{ /*code here*/ }
Body& asBody() override
{ return *this; }
};
struct World
{
void addBody(RestrictedBodyFunctions &body)
{
m_bodies.push_back(&body);
}
void step()
{
for (auto *b : m_bodies)
{
myLog << "Stepping << " b->asBody().getName() << '\n';
b->step();
}
}
private:
std::vector<RestrictedBodyFunctions*> m_bodies;
};
That way, users can create Body objects using createInWorld, but they only get a handle to (the public part of) Body, while the World gets its handle to RestrictedBodyFunctions.
Another option you have is to reverse the above idea - provide a restricted public interface PublicBody, and have Body derive from PublicBody. Your internal classes will use the full Body, while factory functions make sure only PublicBody-typed handles are available to the clients. This alternative is a more simple design, but provides less control over who can access the full functionality.

Related

Are empty overridden methods a sign of bad interface design? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
Improve this question
I was wondering if empty overridden methods inherited from an abstract interface class are a sign of bad interface design. Sometimes interfaces contain methods that are useful only partially for all the possible implemention classes; in the classes where unused methods are not necessary, they are just left empty.
In the following example, connect() and disconnect() are common to the two implementation classes IpConnection and SmtpConnection. However, prepare() is not necessary in SmtpConnection and is left empty.
In this kind of situations, is it better to remove prepare() from the abstract interface IConnection and call it explicitly, or leave it empty? What if empty (unused) methods grow more and more?
#include <memory>
class IConnection
{
public:
virtual void connect() = 0; /* common */
virtual void disconnect() = 0; /* common */
virtual void prepare() = 0; /* partial */
};
class IpConnection : public IConnection
{
public:
void connect() override { /* ... */ }
void disconnect() override { /* ... */ }
void prepare() override { /* ... */ }
};
class SmtpConnection : public IConnection
{
public:
void connect() override { /* ... */ }
void disconnect() override { /* ... */ }
void prepare() override { } /* empty */
};
int main()
{
std::unique_ptr<IConnection> connection;
connection = std::make_unique<SmtpConnection>();
connection->connect();
connection->prepare();
connection->disconnect();
}
An interface is a type of 'contract' between two modules. Typically, an interface specifies how another module is allowed to make use of the functionality of the implementing module instance.
So in fact the interface has no business with the implementation itself. It just sets out the rules, possibly some induced flow constraints and protection provisions that any implementation must adhere to in order to provide a functional implementation.
So, if the interface needs to be overriden with an empty body, that' is totally fine. Other implementations may very well need to do work. Of course if you know that that is never going to happen, well perhaps is better not to over-design at that point, and just remove the interface call.
In your case I would not worry too much and leave it as an interface. Calling functionality directly makes sense ONLY if the overriding method is quite specific to the flow of that implementation, and less useful for other implementations to worry about.

How to access a private variable which is within a function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
#include <iostream>
using namespace std;
class Test{
public:
int kk(int b){
return a=b+5;
}
private:
int a;
/*void priv()
{
int a; // How to access a , if this part was not commented
}*/
};
int main()
{
Test kris;
cout<< kris.kk(5)<<endl;
return 0;
}
I was trying to understand the concept of private and public members and the methods to access the private members when they are defined in a class. I wanted to rephrase the question to how to access a variable, which is local to a private function via an object of class "Test" (as defined in the code).
I found the answer to it and experimented it with my own code and i was able to execute the code. Below is the code
#include <iostream>
using namespace std;
class Test{
public:
int xyz_1(){
return xyz_2() ;
}
private:
int xyz_2(){
int a=5;
return a;
}
};
int main()
{
Test kris;
cout<< kris.xyz_1()<<endl<<"Sorry for the confusion"<<endl;
return 0;
}
How to access a private variable which is within a function
You're trying to access a local variable of priv() in the function kk() which is impossible unless the visibility of the variable a is either public or outside the function (in case with classes) under private: (which will make it accessible to all member functions). In a rough way, you're trying to do something:
void fun1() {
int a;
}
void fun2() {
std::cout << a;
}
Which is not possible.
You might need to think more about your design and what you achieve.
Do you want to have a private member in the class to access the function? Then declare your variable "a" as a private member in your class, and use this.a inside your function. If you want a child class to be also able to access your private member, make the variable protected instead of private.
If you want to restrict any other function in your class from accessing that member, then I would be curious about what your intention is. If you try to hide the implementation you might want to look into the Pimpl technique. However, it also has a very specific use case (besides that you can use it to hide the implementation from developers, too).
https://en.cppreference.com/w/cpp/language/pimpl[pimpl programming technique]1
If you add more information about your problem and intention I'm sure people can give you better directions.

Decouple visualization methods and application [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
this is my first question on SO, so please bear with me.
We develop an application, which gathers data, and we have methods that let us visualize the data in various ways. With growing number of methods, we decided to separate the application and the visualization methods. I'm wondering what is the best way to accomplish this. I've come up with the following code, which somewhat tries to separate the two, but still ...
Is there a better way to do it?
// forward declaration
class App;
// Interface to all visualization methods
struct Methods {
virtual void show(App * a) = 0;
};
// Some visualization method
struct Method0 : public Methods {
void show(App * a) {
a->getData();
}
};
class App {
public:
vector<Methods *> methods;
void run() {
// draw all registered methods
for (auto m : methods)
m->show(this);
}
int getData() {
// parse and precompute data (time-consuming, thus do it only once)
// return the required data (not just an int..)
return 42;
}
};
void main() {
App a;
// register some methods
a.methods.push_back(new Method0());
// run the application
a.run();
// clean up
for (auto m : a.methods) delete(m);
}
EDIT
I think Alexander and Petr pointed me in the correct direction, thank you. I'll follow Petr's suggestion and try to separate the data into another class.
Addressing the comment by Spektre:
Developed on Windows (MSVC), otherwise platform independent.
The visualization is mostly static and changes based on user input. I guess 10 updates per second is an upper bound on the refresh rate.
What do you mean by data transfer times?
Memory is not an issue.
The data is a bunch of vectors of objects holding other vectors of objects, 5 dimensions in total.
One visualization is similar to ROC curve, containing several curves, so we need to traverse part/all the dimensions and compute some statistics. The result is shown in the following figure.
What you have there already looks quite good. As you have probably already assumed, you are not the first person to have this kind of problem. The standard solution for the separation of your data from your visualization is known as the Model View Controller Pattern (MVC), which not only decouples the presentation of your data from the data itself, but also allows for simple manipulation of the data from the display.
If you just want to display your data, then you might want to have a look at the Observer Pattern. Then again, what you have is already quite close to this pattern.
In addition to an answer by Alexander, I will mention that actually you did not completely separated data and visualization. The Application class still knows both about the internal structure of data and about the vector of visualization methods. What you should better do is to have a separate class, say Data, the will be doing all the computations you need, and then have the main class (App for example) that will just handle registration of methods and passing data to them.
Something like
class Data;
struct Methods {
virtual void show(Data * a) = 0;
};
struct Method0 : public Methods {
void show(Data * d) {
d->getData();
}
};
class Data {
public:
int getData() {
// parse and precompute data (time-consuming, thus do it only once)
// return the required data (not just an int..)
return 42;
}
}
class App {
public:
vector<Methods *> methods;
Data* data;
void run() {
// draw all registered methods
for (auto m : methods)
m->show(data);
}
};

Is there anyway in c++ to make a function of a class who's objects each do something different for that function? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Just some background:
I am making a monopoly game and now I have to implement the actions of each space such as GO, properties (upgrading), chance, community chest, jail, etc.
I've considered making a different class for each space (but obviously that would be very time consuming). I believe there is also a way do to it with inheritance and pure virtual functions. Any way you guys can think that would make this a simpler process?
Thanks!
There are only a few different types of spaces:
properties
railroads
chance / community chest
utilities
other single ones like go, jail, parking, tax
For example you could have a Property class where each instance of the class has a different name/colour/price. You wouldn't have to make 22 different classes, just have 22 instances of the same class with different names.
Note that having class instances that represent spaces you can land on is only one way to implement a game like that. I'm pretty sure I wouldn't choose that option.
There are two ways you can make a function do different things given an object:
Differentiate the behavior based on the data of the object.
You could capture the differences in the various spaces using data.
enum SpaceType
{
GO, CHANCE, COMMUNITY_CHEST, // etc...
};
class Space
{
public:
void foo()
{
switch (spaceType)
{
case GO:
// DO stuff for GO
break;
case CHANCE:
// DO stuff for CHANCE
break;
// etc..
}
}
private:
SpaceType spaceType;
}
Differentiate the behavior based on the type of an object.
class Space
{
public:
virtual void foo() = 0;
};
class GoSpace : public Space
{
public:
virtual void foo()
{
// Do stuff for GO
}
};
class ChanceSpace : public Space
{
public:
virtual void foo()
{
// Do stuff for CHANCE
}
};
// Similarly for other classes.
Pick your method. Personally, I would pick the second method because the logic for each different type is put into their own functions, without the complications of what other types do.

Differentiating between data class and logic class in agile [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I've been reading an agile book about clean coding, mainly in Java and c#. Considering the concept of differentiating between a data class and a logic/object class. I have the following situation in c++, where I can't decide which variant is a clean code. I have a Plane class with some attributes and these attributes change when only one of them changes, so
First Method
class Plane3D {
public:
BBox bbox;
float l,w,h;
void setbbox(BBox bbox) {
this->bbox = bbox;
recalculateLWH();
}
void setLWH(float l, float w, float h) {
//set here
recalculateBBOX();
}
};
This makes sense to me, since to the user he is just calling one method and doesn't have to care about internal work of the class. but this is a violation for a data class, that it contains logic
Now the
Second method
class Plane3D {
public:
BBox bbox;
float l,w,h;
void setbbox(BBox bbox) {
this->bbox = bbox;
}
void setLWH(float l, float w, float h) {
//set here LWH
}
};
int main() {
BBox bbox;//init here
Plane plane;
plane.setBBox(bbox);
recalculateLWH(plane);
}
Now the second method actually separates the data class from the implementation but it increases the responsibilities of the class user and forces him to make an extra call. To my understanding the second method is the correct one from an agile POV, but I find the first method more logical to use.
I'd like to know which of the two methods would make more sense for you guys to undertsand and use
Regards
In this case I think you should prefer first method to second.
Your method calls should transform object from one correct state to another correct state. Using the second method after your setBBox(bbox); call your object moves to some incorrect state indeed.
But 'logic class way' can however take place in another situation.
Consider you should move plane:) from hangar to landing strip. Now it will be naturally to introduce new class named Tractor and use it like tractor.move(plane)