Access object from other file

How would I access an object from another file?

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

class test {
public:
    int random_number = 2;
};

int main () {
    test t1;
    t1.random_number = 3;
    std::cout << t1.random_number << std::endl;
}


How would I access the object t1 from another file?
For example test.cpp / test.h
Last edited on
Internet search:

c++ with header and cpp file

I like to have my header files with hpp extension - it means a c++ header file :+)
How would I access the object t1 from main.cpp to test.cpp?
Normally, you wouldn't. They are in different Translation Units (TU)

To create an object of type test include the test.hpp file. The class has functions which can take arguments of different types, so for example if a class foo wanted to do something with a test object, then one of its functions would accept a test as a parameter.

This raises a whole lot of questions, I suggest you read up a bit.
So how would I do the above context?
You created t1 in main. ideally you want to have a separate file for each class including main. Then in your main file you will include all the other files (classes) and create the objects in main NOT in another file and try to bring it over. Hope this helps!
Topic archived. No new replies allowed.