Access the main() from an instantiated class

Pages: 12
Hello everyone,

as the title say, i can access the main vars, property and methods from an instantiated class?

I mean:

in the main class i create an instance of a class

int number_of_animals=100;

int main ()
Animals dog;


Now, it's possible in the class Animals have access to the number_of_animals or any other vars, properties, methods...

thank you in advance
There are a few ways you could have access to them but all of them require something...

1. pass the vars to the constructor and save it inside the class
2. make a header file with global vars and include that file in your animals header file
3. declare the vars above the animal class
4. when calling a function pass those that are needed...

I don't know what it is you wanna do but it looks like you are just playing around and learning C++ :)
Yeah, learning...

I've tried many years ago (Turbo c++ anyone?). After years of VB, actionscript, Pascal, java, and so on... never tried advance my c++ knowledge in the past

i really need to study.

Then I wish you best of luck :)

You could also make a public static variable in the class itself...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Animal {
public: 
    static int number_of_animals;

    // ...
};
int Animal::number_of_animals= 100;

int main()
{
    Animal dog;
    std::cout << dog.number_of_animals<< std::endl;
    std::cout << Animal::number_of_animals<< std::endl;


    return 0;
}
Last edited on
Thank you for the reply.

In the code you've posted i can access the animal class from the main() and this is ok.
Btw, i would like to access the global variable that are present in main(). The Animal class reside in an file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

int sheep = 10;
string sheep_name="Pluto";

struct my_Animal {

string name;
int in_stable;
};

int main()
{
    Animal dog;
    std::cout << dog.number_of_animals<< std::endl;
    std::cout << Animal::number_of_animals<< std::endl;


    return 0;
}


//assuming this is the file Animal.h
1
2
3
4
5
6
7
class Animal {
public: 
    static int number_of_animals;

    // ...Here i want to check or access the struct my_animal, the sheep_name or the other global var of the main file.....

};
Last edited on
Someone can help me in this?
Btw, i would like to access the global variable that are present in main()
Which variable? You cannot access variables located in one function from another function.

You can access a static variable from a class/struct like so:
Animal::number_of_animals

Note that number_of_animals is only a declaration. You need to define it [within a cpp] like so:

int Animal::number_of_animals = 0;

otherwise you will get unresolved error from the linker.
Last edited on
Forget all of the above:

i have:

#include<iostream>
#include<vector>....
#include <myClass.h>

using namespace std;

//gloval var here....

int age=99;


int main() {

//create an instance of myclass here.

}


From within myclass a method needs to acce the age value

How can i do this?

tried with extern int age=99; too
You could pass the value into the constructor of the class, so that it stores a copy of the value. That's a better solution than using global variables; global variables are rarely a good solution to anything.
Assuming that the value to pass into the constructor is a vector or a struct, how to keep those updated?
Inside myclass.cpp, just put this near the beginning:
extern int age;
You mean you want to change the contents of the vector or struct in one place, and for the object to have access to the changed values?

In that case, you want to pass a reference to the vector into the constructor, or possibly a pointer. Although be sure you understand the ownership and lifetime of the vector, and have designed your code so that the class never ends up trying to use the vector after the vector has ceased to exist.
You can access them with the dot operator. Not sure if that answers your question, MikeyBoy's answer might be what you want instead. My code is copying the vector into the class instance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <vector>
#include <iostream>
class MyClass {
public:
    MyClass(const std::vector<int>& vec)
    : my_vector(vec)
    {}
    std::vector<int> my_vector;
};

int main()
{
    MyClass c(std::vector<int>{1, 2, 3});
    c.my_vector.push_back(23);

    std::cout << c.my_vector[3] << std::endl;
}

Edit: Fixed code
Last edited on
@dhayden the extern int age should reside both in the main file and in the class?

@Ganado
what you are pointing out is interesting, but difficult to understand for me.

I should pass in the constructor a const std::vector<int>& referenning the "vec", but what the meaning of the : my_vector(vec) {} and the following line: std::vector<int> my_vector;

Could you please explain better?


Thank you very much
and the following line: std::vector<int> my_vector;

That's the declaration of a member variable inside the class. It's the same concept as the class you posted
1
2
3
4
struct my_Animal {
  string name;
  int in_stable;
};

That class has "name" of type string and "in_stable" of type int. But in my above example, it's simply a vector instead of an int or string because it sounded like you wanted to see a vector in a class as example.

What's the meaning of my_vector(vec) {}

Oh, that's just a way to initialize member variables instead of assigning them after construction. It's better performance wise.
If it's confusing just do
1
2
3
4
MyClass(const std::vector<int>& vec)
{
    my_vector = vec;
}

it accomplishes the same thing.
Last edited on
Yes, i'm really confused :P

I'll try to explain better the situation

i have to say that the type of vector isn't int, btw, but a number of instantiated class Animal that i push in the vector.

i do the following:

extern std::vector<Animals> my_anymals;

Animal dog ("Pluto", 10, 40);
Animal cat ("Silvester", 5,10);

then i do:

my_animals.push_back(dog);
my_animals.push_back(cat);

now, how my Animal class should look like to access the vector my_animals that reside in the main.cpp declared in his global space?

Could you please provide an example?

Thank you in advance


"Oh, that's just a way to initialize member variables instead of assigning them after construction. It's better performance wise."

I've learned another thing :P
Last edited on
now, how my Animal class should look like to access the vector my_animals that reside in the main.cpp declared in his global space?

Why can't you do what's already been suggested - pass that vector to the class as an argument to the constructor?

You never answered the question you were asked:

MikeyBoy wrote:
You mean you want to change the contents of the vector or struct in one place, and for the object to have access to the changed values?
"You mean you want to change the contents of the vector or struct in one place, and for the object to have access to the changed values?"

Yes, i want to to this too, but the primary goal (at the moment) is to access the vector my_animals as i describer in this post: http://www.cplusplus.com/forum/beginner/168190/#msg844484

I've tried the suggestions above but haven't worked.
i get an error. Maybe the problem is that the vector is not a vector<int> type, but it's a vector<Animals> type?

I will retry, hoping that i've forgotting something, and i'll post any compiler error.

Thank you very much
Last edited on
@dhayden the extern int age should reside both in the main file and in the class?


Sort of. This gets to the difference between declaring a variable and defining it. When you declare a variable, you tell the compiler the variable's name and type. When you define a variable, you also tell the compiler to allocate memory for it. Most of the time, you define variables:
int myint=4;

You can declare a variable by adding extern, and by NOT giving it a value:
extern int myint;
It's important to understand that you can declare a variable any number of times in any number of files, but you can only define it once. This makes sense if you think about it: you have to tell the compiler to allocate space for the variable once, but you can tell "hey, there's a variable called myint" as many times as you want.

So why would you do this? For the exact problem you're facing! When you need access to the same variable in two different files. In that case, you can define the variable in one file, and they declare it in the other(s).

Usually there are several variables and classes that you need to declare, so the declaration goes in a header file and you can #include the file whereever you need it:

animals.h:
1
2
3
4
5
class Animals {
    ....
};

extern int number_of_animals;


animals.cpp:
1
2
3
4
5
6
7
#include "animals.h"

int number_of_animals;   // define number_of_animals
void f()
{
    std::cout << number_of_animals;
}


main.cpp
1
2
3
4
5
#include "animals.h"
int main()
{
    std::cout << number_of_animals;
}


Note that this is all for illustration. It would be better to use one of the standard containers to store your animals and use the container's size() method to get the number of animals.
I've tried the suggestions above but haven't worked.
i get an error.

Is there any particular reason you're not telling us what the error is, nor showing us the code that causes the error? Do you not want us to be able to help you?

Maybe the problem is that the vector is not a vector<int> type, but it's a vector<Animals> type?

That's unlikely. A vector can hold any object type, within certain restrictions. But, again, since you don't seem to want to actually show us your definition for the Animals class, it's hard for us to know whether it conforms to those restrictions.
Pages: 12