0

I've created one function which generates a code table and another function which performs a table look up based on some parameters which are passed through it. Eg.

generateCodeTable(int x, int y);

tablelookup(int z);

I've just realized that the variables created by the generateCodeTable function are out of scope and can't be accessed by tablelookup(). I could avoid this by initializing the variables before I call the generateCodeTable function but I was wondering if there was a more elegant way to implement it.

Thanks

Minh
  • 1
  • 1
    are these functions members of a class? What does `generateCodeTable` do - does it populate an local container/global container etc.? need more information to provide a useful answer... – Nim Jan 03 '11 at 12:31

3 Answers3

4

There are many ways. You could make both functions take a parameter that is the code table and pass the same object to both functions

Or you could make a CodeTable class which contains the data and performs the generateCodeTable functionality in its constructor and has a lookup member function that performs the tablelookup functionality.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • Much appreciated. Guess I'll spend some time learning about classes. – Minh Jan 03 '11 at 12:55
  • +1. There is no point of using C++ if the advantage of class is not taken. – taskinoor Jan 03 '11 at 12:55
  • @Minh: Definitely do that. Spend some time with a good beginners C++ book. http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – CB Bailey Jan 03 '11 at 13:01
1

Do you know classes?

struct MyCodeTable
{
  MyCodeTable(int x, int y)
  {
    // initialize your table
  }

  void lookup(int z)
  {
    // to something with your table
  }

private:
  std::map<YourKey, YourValue> table_; // or whatever the type of your table is
};
Karl von Moor
  • 8,484
  • 4
  • 40
  • 52
  • Seems we were writing the answer at same time. Though you are more verbose than me. +1 for that. BTW, is there any specific reason of using struct instead of class? – taskinoor Jan 03 '11 at 12:53
  • @taskinoor: I don't need to write a `public:` line, but that's not really a good argument :D I just personally prefer it – Karl von Moor Jan 03 '11 at 13:48
0

If the methods are part of a class then make the variables member of the class. And if the methods are not part of a class then instead of making global variables and trying other stuffs(one is already explained by Charles Bailey, I'm not going to write again), use a class. Otherwise no point of using C++.

taskinoor
  • 45,586
  • 12
  • 116
  • 142