all
all

Reputation: 324

Structure of program

I have few files:

main.cpp:
int main{
...
while(1){
...
draw();
...
}
...
return 0;
}

and draw.cpp: I want to see objects and all manipulations here. I cant make objects local to draw(), because draw() is inside loop, so I will get many object constructor/destructor calls - so they are global. Also I ve made init block to prevent unnecessary calls/assignments

draw.cpp:
Object A, B;
int initialized = 0;
void draw(){
if(!initialized){
    A.initialization;
    B.initialization;
    initialized = 1;
}
A.move(1,1);
B.rotate(45);
}

It works, but Im looking for better way to organize my code
Added:
Thanks for answers, looks like I have to read something about pattern designs

Upvotes: 0

Views: 188

Answers (2)

Shash316
Shash316

Reputation: 2218

Option 1

Define a new Class called Draw and put the attributes into it. You need to modify main and draw files for this. With this you can avoid declaring anything global

Option 2

Define a class within draw.cpp called draw and add your current global variables as static member variables. Initialize and use them using static functions. With this you dont have to change main. This design technique is called Singleton (one of the design patterns)

Example code draw.cpp

class Draw
{
public:
  object A, B;

  static void init()
  {
    // init A
    // init B
    isInitialized = 1;
  }

  static int isInitialized;

  static Object & getA()
  {
     if(isInitialized == 0)
     {
       init();
     } 
     return A;
  }
  // similarly B

};

Upvotes: 1

tp1
tp1

Reputation: 1207

Here's steps to make it work better:

  1. Add a struct containing all your objects near main().
  2. pass it to draw(MyStruct &s); via reference parameter.
  3. you're done.

Upvotes: 2

Related Questions