Classes and scope

I have some piece of information and I want to change it in different ways, one change at a time. After each change the next change depends on some input.

For example we have int x=0; and we can either add or subtract 1. After adding or subtracting we get some input 'a' or 's' that determines if the next change will be add or subtract. This is a simplified example and in theory this needs to handle any set of information that could be changed an infinite number of ways.

My first approach was to make 3 classes that looked something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Start{
   int x;
public:
   void begin()//Pretend definitions are in a separate .cpp
   {
      char c;
      cin>>c;
      if(c=='a'){Addition add(&x)}
      if(c=='s'){Subtract sub(&x)}
   }
   Start()
   : x(0){begin();}
};

class Addition{
   int* x;
public:
   void add()
   {
      *x=*x+1;

      char c;
      cin>>c;
      if(c=='a'){Addition add(&x)}
      if(c=='s'){Subtract sub(&x)} 
   }
   Addition(int* i)
   :x(i){add()}
};
//And a subtract class that's the same as Addition but with *x=*x-1; 

To start I just Instantiate a Start in the main and from there it loops forever.
Each class calls its only function in the constructor and will always Instantiate a new class within itself.

My question is, will this eventually use all the memory in the stack? As far as I can tell nothing ever goes out of scope because its just an infinite chain of classes in classes in classes...

If this is a terrible way to go about doing this, which I'm assuming it is, what other ways are there to approach this?
Okay friend,

Yes that's a bad design it's "recursive" (which doesn't mean resursive is a bad design just in this case not the way to go).
You would have to type in a loooooooooot of a's and c's to run out of stack-memory but if you would abandon life for a week you might get there.

Well why don't you use a loop?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int x;
Addition addobj;   //you would need a default constructor of course
Subtract subobj;  //same here

do {

char c;
cin>>c;

switch(c) {
case 'a': addobj.add(&x); break;
case 's': subobj.sub(&x); break;

}while(c != 'n'); //if cin is 'n' stop
}


//make add/sub method look like this of course:

   void add(int &x)
   {
      x++;
   }


There is no "infinite" number of ways to change your information.
You have to implement every way and then think about some clever way to make it work the way you want.

Looks for me just like a task requiring great diligence. Have fun!

ps: creating a class just for one "add" method or one "sub" method sounds like overkill maybe it's enough just to create stand-alone add and sub functions or one big class containing all kinds of arithmetic stuff
Last edited on
You can just integrate it into one class.



Topic archived. No new replies allowed.