C++ / Qt QTime - How to use the object

1.4k Views Asked by At

this is more a generell C++ beginner Question:

I have 2 classes:

  • Class A, including a 'ReadData' Method, which is called as soon as new Data is received by a TCP Socket
  • Class B, including a Method 'Start' which is sending big amounts of data via TCP.

Due to the architecture, its not possible to have both methods in one class.

What I want to do:

  1. Start a Timer as soon as 'Start' in Class B is invoked.
  2. Stopp the Timer as soon as the 'ReadData'in Class A is invoked.
  3. Then i will calc the difference to see how long it took...

My Question:

  • Where do I create the Object:

    QTimer transferTimer;
    
  • How can I pass the Object to my both Classes?

How is the proper way in C++ to handle this?

Thank you.

1

There are 1 best solutions below

8
vahancho On BEST ANSWER

Here is one of the possible solutions. It's simplified to demonstrate the idea:

class C
{
public:
  void start()
  {
    m_startTime = QTime::currentTime();
  }

  void stop()
  {
    m_endTime = QTime::currentTime();
  }

  int difference() const
  {
    return m_startTime.secsTo(m_endTime);
  }

private:
  QTime m_startTime;
  QTime m_endTime;
};

class A
{
public:
  A(std::shared_ptr<C> c) : m_c(c)
  {}

  void ReadData()
  {
    // ...
    m_c->stop();

    int transferTime = m_c->difference(); // seconds
  }

private:
  std::shared_ptr<C> m_c;
};

class B
{
public:
  B(std::shared_ptr<C> c) : m_c(c)
  {}

  void start()
  {
    // ...
    m_c->start();
  }

private:
  std::shared_ptr<C> m_c;
};

int main(int argc, char ** argv)
{
  auto c = std::make_shared<C>();
  // a and b keep reference to instance of class C
  A a(c);
  B b(c);

  [..]
  return 0;
}