0

First of all, I think this problem has already been discussed and is pretty common but id doesn't seem to find an answer appropriate to my problem. My problem is related to circular dependencies, which by itself can be solved by using forward declaration, however, in my case, I need to know more then the class name in the forward declaration (like attributes and functions).

In my code both classes, Time and Distance/Speed need to know each other and each other attributes. I avoided the problem by declaring an "Interface" of Time which contains the attribute that is needed for Distance/Speed, but I'm wondering if there is a more elegant solution to this problem that wouldn't involve creating an "Interface".

class ITime
{
public:
    ITime(float s) :time_s(s) {};
    float time_s;
};

class Speed
{
public:
    Speed(float ms = 0) :speed_ms(ms) {}
    float speed_ms;
};

class Distance
{
public:
    Distance(float m = 0) :distance_m(m) {}
    float distance_m;
    Speed operator/ (const ITime& t) const
    {
        return Speed(distance_m / t.time_s);
    };
};

class Time :public ITime
{
public:
    Time(float s):ITime(s) {}
    Distance operator *(const Speed& speed) const
    {
        return Distance(time_s * speed.speed_ms);
    }
};
palkenas
  • 19
  • 4
Romain
  • 1
  • See [How to create two classes in C++ which use each other as data?](https://stackoverflow.com/questions/4964482/how-to-create-two-classes-in-c-which-use-each-other-as-data) – Jason Aug 06 '22 at 14:42
  • @JasonLiam I am not convinced the questions linked above address the actual problem. Imho the issue is more of a design one i.e. putting logic in classes for the wrong reason (simply because of the order of operator parameters) which creates unnecessary coupling.@Romain I believe a better solution (cannot post as an answer anymore) would be to extract the operators out of the classes as free functions. – rucamzu Aug 06 '22 at 14:51
  • 1
    @rucamzu Do you mean implementing the member functions outside the class, once they(the classes) have been defined? The first [dupe](https://stackoverflow.com/a/72474240/12002570)'s method 2 covers that. – Jason Aug 06 '22 at 14:54
  • @JasonLiam it does a forward declaration of `Entity` and implements `Weapon::Attack` still as a member but out of the class definition (which should be usual in C++). What I suggest here is for the operators to not be members in the first place. – rucamzu Aug 06 '22 at 15:51
  • @rucamzu Ok, I think your comment that those `operators` can also be made free functions is hint enough for OP and doing that is trivial. – Jason Aug 06 '22 at 16:25
  • @rucamzu thx for your answer, not putting the operator as member function seams to be the write solution. – Romain Aug 06 '22 at 21:36
  • 1
    @JasonLiam thx to you too, the discussion you linked was interesting. – Romain Aug 06 '22 at 21:39

0 Answers0