Thread: How can I access global variables in this program inside member function.

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    76

    How can I access global variables in this program inside member function.

    I want to access x(100) and Y(200) into member function(fun()) - how to do that?

    Code:
    #include<iostream>
    using namespace std;
    int x=100;
    int y=200;
    class A
    	{
    		int x;
    		int y;
    		void fun(int x, int y)
    			{
    				cout<<x<<endl<<y<<endl;
    			}
    	};
    
    
    int main()
    	{
    		A o={3,5};
    		o.fun(78,56);
    		return 0;
    	}

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    There's a special unary operator for that, "::".
    Code:
    cout << ::x;
    Devoted my life to programming...

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Why are you using global variables in the first place?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Yeah, this doesn't seem like the best design. But as a matter of technicality, it can be done.

  5. #5
    Unregistered User Yarin's Avatar
    Join Date
    Jul 2007
    Posts
    2,158
    Quote Originally Posted by laserlight View Post
    Why are you using global variables in the first place?
    Because they can

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to access my member variables from main?
    By Alexius Lim in forum C++ Programming
    Replies: 3
    Last Post: 11-10-2013, 06:48 AM
  2. HELP! Multiple threads access to global variables
    By thilar in forum C Programming
    Replies: 10
    Last Post: 10-29-2012, 06:46 PM
  3. Efficiently access member variables
    By cyberfish in forum C++ Programming
    Replies: 9
    Last Post: 04-03-2012, 06:38 AM
  4. member function or global?
    By CodeMonkey in forum C++ Programming
    Replies: 2
    Last Post: 06-17-2010, 03:48 AM
  5. Providing access to member variables between classes
    By Tonto in forum C++ Programming
    Replies: 11
    Last Post: 06-19-2006, 01:06 PM