assessing a variable from some other class


Hi Again all,
Please look into my package structure below. I am trying to access a variable of Parser class from callsomemethod() method of a different class. I don't want to pass this through arguments since the function calls many other functions in between and I will have to change many files. Basically I just need a variable t that I can access and update from all the classes.
Please help



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Parser.h
parser class{


public:
int t= 0;

};



Exec.cpp
---------  
#include "Parser.h"

main()-- HERE IS WHERE MY PROGRAM WILL START
{
Parser pParser; 
pParser->t= 1

callsomemethod() 

}


someother.cpp
----------
callsomemethod()
{

// CAN WE ACCESS THE pParser->t variable from here without passing it though function

}
Last edited on
Syntactical check : you're creating a stack based Parser object and trying to dereference it like a pointer using the -> operator. Try the '.' operator instead ;)
And pretty much the only way you're going to be able to access that Parser object without passing it as an argument is to make the object global and make it extern.

http://stackoverflow.com/questions/15841495/the-usage-of-extern-in-c
Or he could simply make it static then access it like parser::t

Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

void foo( void );

class Test
{
    public:
        static int a;
};

int Test::a = 0; //initializing

int main()
{
    std::cout << Test::a << std::endl;

	Test::a = 10;
	std::cout << Test::a << std::endl;
	
    foo();
    std::cout << Test::a << std::endl;

    return 0;
}

void foo( void )
{
    Test::a = 100;
}


http://ideone.com/vxp7c8
thanks.. it worked:)
Topic archived. No new replies allowed.