Originally Posted by
xconspirisist
Presume that main is not allowed to call func_2
Does this mean, if the class is initialised in main, that they only way to use it in func_2, is to pass it to func_1, then onward to func_2?
If the object is not global and was instantiated within main, then the only way to use it in func_2 is for it to have been passed into the function starting from main and then through func_1.
Originally Posted by
xconspirisist
If I shouldent use a global variable at the top of the file:
Because apparently global variables are bad, also, I would have no way of accessing it from any other file.
If I declare it in a header, presumably so all files could access it, in the method above I'll get errors during link, about the variable already being defined...
Accessing it from another file? You mean you have a multi-source file program and you are instantiating an object in one of the source files and need to use it in another source file? If all the source files include the header file that holds the description of the class then there should be no problem with having a function in one of the other source files that accepts an argument of that class/type, you just end up passing the object from function-to-function regardless of what source file the function is defined in.
Class.H
Code:
#ifndef CLASS_H
#define CLASS_H
class myclass_t
{
bool value;
public:
...
};
#endif
Func.Cpp
Code:
// Include Class.H so this source file knows what a myclass_t object looks like
#include "Class.H"
void func(myclass_t myclass_h )
{
// Do stuff with myclass_h passed in from other source file
}
Main.Cpp
Code:
// Include Class.H so this source file knows what a myclass_t object looks like
#include "Class.H"
// Prototype function defined in other source file as extern
// You could put this prototype in a header of its own if needed
extern void func(myclass_t);
int main()
{
myclass_t myclass_h; // Create an instance of a myclass_t object
func(myclass_h); // Call function defined in other source file
return 0;
}
[edit]
Code:
if ( myclass_h.read_value() ) {
cout << "Value is true.";
} else {
cout << "Value is false.";
}
If you are going to be doing this sort of thing often, you might want to just overload the stream insertion << operator:
Code:
#include <iostream>
class myclass_t
{
...
friend std::ostream& operator<<(std::ostream& os,const myclass_t& rhs);
};
...
std::ostream& operator<<(std::ostream& os,const myclass_t& rhs)
{
if ( rhs.value ) os << "Value is true.";
else os << "Value is false.";
return os;
}
Then you can just say:
Code:
myclass_t myclass_h;
myclass_h.set();
std::cout << myclass_h << std::endl; // Outputs "Value is true"
myclass_h.unset();
std::cout << myclass_h << std::endl; // Outputs "Value is false"
[/edit]