views:

61

answers:

2
+1  Q: 

c++ function scope

I have a main function in A.cpp which has the following relevant two lines of code:

B definition(input_file);
definition.Print();   

In B.h I have the following relevant lines of code:

class B
 {
   public:
     // Constructors
     B(void);                                                    
     B(const char *filename);
     ~B(void);

     // File input
     int ParseLSFile(const char *filename);

     // Debugging
     void Print(void);

     // Data
     int var1; 
     double var2;   
     vector<char* > var3;   
     map<char*, vector<char* > > var4; 
}

In B.cpp, I have the following function signatures (sorry for being redundant):

B::B(void)
  : var1(-1),
    var2(numeric_limits<double>::infinity())
{
}

B::B(const char *filename)
{
  B *def = new B();
  def->ParseLSFile(filename);
}

B::~B(void)
{
  // Free memory for var3 and var 4
}

int B::ParseLSFile(const char *filename)
{
  // assign var1, var2, var3, and var4 values
}

void B::Print(void)
{
  // print contents of var1, var2, var3, and var4 to stdout
}

So when I call Print() from within B::ParseLSFile(...), then the contents of my structures print correctly to stdout. However, when I call definition.Print() from A.cpp, my structures are empty or contain garbage. Can anyone recommend the correct way to initialize/pass my structures so that I can access them outside of the scope of my function definition?

Thanks.

+3  A: 

Instead of making

B *def = new B();
def->ParseLSFile(filename);

in your constructor you should simply write

ParseLSFile(filename);

This means that your current object members would be initialized by using ParseLSFile function. You could probably name that function InitFromFile to preserve some naming logic.

Then your code will transform to:

B object_name(filename);
object_name.Print();

and (not exact, but just for you to understand the underlying mechanics) this would mean somthing like

Create empty object of type B
Initialize it from file using InitFromFile()
Call Print() to display the contents of this object
Kotti
Thanks for the function name suggestion. I've been thinking of a better way to name it and I like yours.
Myx
+2  A: 

In your constructor that takes a const char*, you dynamically create another instance of the class and use that instead of the current instance. Instead of

B *def = new B();
def->ParseLSFile(filename);

you need to just call

ParseLSFile(filename);

so that you are operating on the object being constructed. As it is now, you have a resource leak.

On an unrelated note, you should not use a pointer as the map key. As it is now, it is near impossible to access an element by its key because only a pointer comparison will be done; the string values pointed to by the char* will not be compared. You should use std::string as the key type instead.

James McNellis