jeudi 29 avril 2021

Call function from member class A in member class B

I have a C++ project where a set of settings are calculated by making use of a function inside another member class. In this case the other class is a motor with values acceleration time and speed. The motor class also has a member function that calculates the motion time with input distance.

The settings class should be able to calculate the motion time for different distance inputs and use/store these values. The distance value is known to the settings class but the acceleration time and speed are known to the motor class

Below is a minimum working example of my current solution. At the moment I pass the entire motor class by reference to the settings class so that it has access to "CalculateTime(double distance)". It works but I'm not sure if this is the best solution, I would like to design it according to object oriented best practices.

One possible alternative I can imagine is placing the same "CalculateTime(double distance)" function inside the settings class and then pass the acceleration time and speed values from the motor class to the Settings function (via main.cpp, making it appear a bit messy maybe?).

I have searched for similar questions but I'm having a hard time nailing the keywords to use. Especially for design pattern questions such a this one. One interesting thread I found was this one:

Communication between objects in C++

Here they talk about connectors and interfaces but I must admit I'm not qualified to judge if this case requires such a solution.

main.h

    #pragma once
        
    class Motor
    {
    public:
        Motor();
        ~Motor();
    
        double CalculateTime(double distance);
    
    private:
        double a;
        double v;
    };
    
    
    class Settings
    {
    public:
        Settings(Motor& motorRef);
        ~Settings();
    
        void CalculateTotalTime();
        double GetTotalTime();
    
    private:
        Motor& motor;
        double totalTime_;
        double distance_;
        int steps_;
    };

main.cpp

#include "main.h"
#include <iostream>


Motor::Motor() :
    a(10.0),
    v(0.5) {}

Motor::~Motor() {}

double Motor::CalculateTime(double distance) {
    return a * v * distance;
}


Settings::Settings(Motor& motorRef) :
    motor(motorRef),
    totalTime_(0.0),
    distance_(2.0),
    steps_(100) {}

Settings::~Settings() {}

void Settings::CalculateTotalTime() {
    for (int i = 0; i < steps_; i++)
    {
        totalTime_ += motor.CalculateTime(distance_);
    }
}

double Settings::GetTotalTime() {
    return totalTime_;
}


int main()
{
    Motor A;
    Settings B(A);

    B.CalculateTotalTime();
    std::cout << B.GetTotalTime();

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire