how can I access public variables and functions that I've created in some classes from a global function. Is it possible?
My problem - I've made several classes. All with their variables and functions. At the moment, all they are doing are asking questions on the screen and saving the input data into them. Now i need to write them in different ".txt" files. I though to make a global function that would print on the screen all the data that was inputted during the process and then if the users accepts, it would be written in the .txt files.
class Person
{
public:
int age;
};
int main()
{
Person bob;
bob.age = 23;
Person jane;
jane.age = 21;
// If you are trying to access "age", you can:
cout << bob.age; // print bob's age
cout << jane.age; // print jane's age
// however note that you need an object (bob or jane, in this case).
// you can't simply access "age" by itself:
cout << Person::age; // ERROR.. whose age? bob's? jane's? Someone else's?
}
Member functions behave the same way.
So there's no trick or anything. As long as the member you want to access is public, you can access it. You just need an object.
General answer: All you have to do is create an instance from your class with this global function. Then you can use that object you created to access the member functions you need.
1 2 3 4 5
void GlobalFunc()
{
CatClass Fluffy; //i want to hear a cat meow
Fluffy.Meow(); //yay !!!
}
1 2 3 4
void GlobalFunc()
{
Meow(); //compile error: how can i hear a cat meow if there is no cat ?
}
Depending on the complexity and size of your program, you may want to create another class for the input and output to file so that you can do something like this: