Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exchange data between classes?

Tags:

c++

I'm learning C++ and moving my project from C to C++. In the process, I stumbled on this problem: how to save/update variables that are in use in several classes? In C I used global variables, but it is not good for C++.

So, let's assume we have 4 classes:

class Main_Window
{
    //...
    void load_data_menu_selected();
}

class Data
{
    //...
    double *data;
}

class Load_Data
{
    //...
    double *get_filename_and_load();
}

class Calculate
{
    //...
    int do_calculation()
}

So, Main_Window is class for application's main window where it interacts with user input etc.
I want to do:

  • create an instance of class Data in the Main_Window
  • use Load_Data for loading data from file and store it in the Data
  • use Calculation class for doing something with read data in Data class
  • The question is: where I should create classes, to make Data class members available from other classes. Should I use Inheritance?

    like image 771
    Daniel Uspensky Avatar asked Dec 20 '10 10:12

    Daniel Uspensky


    2 Answers

    Start from observing what are possible relations between instances of two classes. Let us say a is an instance of class A and b is an instance of class B. If a uses b, class A can have as its member instance of class B (b), pointer to b (which is of type B*), or reference of b (which is of type B&). If only one method of class A uses b, you have again same three options: B, B* or B& can be method's arguments. Having B* and B& as class members suggests that a does not control b's lifetime so class A must have a method that sets these members through its parameters. The question of ownership (objects' lifetimes) has a big role in design of relationship between classes. Main relationships are briefly described in this article.

    like image 76
    Bojan Komazec Avatar answered Sep 22 '22 09:09

    Bojan Komazec


    I think you only want to have a Main_Window class, and the rest should be members of that class.

    class Main_Window
    {
     private:
     DataObject windowData;
    
     public:
     void loadData(string fileName);
     void calculate();
    }
    

    Inside the loadData and calculate methods, you will be able to access the same data with this->windowData . Sorry if my syntax is bad, my c++ is rusty

    like image 43
    Matt Avatar answered Sep 18 '22 09:09

    Matt