Computer Programming web Web programming Tips



Variable scope - Computer Programming For Beginners

By Sergey Skudaev

The following C++ code example includes declaration of message variable inside Greeting class, inside PrintMessage method of the class and inside the main function. In each place message variable is assigned different values. Inside class message="Hello World\n", Inside PrintMessage function message="How are you?" and inside main function message="Hi There". When you execute the program, command prompt window display: "How are you?" because class level variable is not visible inside the PrintMessage function in scope of the local variable with the same name. A variable inside the main function and outside the class is most global and therefore it is not visible as well.

If you comment the line message="How are you?", compile and execute the code again command prompt display "Hello World" Now class level variable becomes visible. The variable message inside the main function and outside the class is more global than class variable and is not visible inside the class in scope of class variable with the same name.It is visible outside the class. If you copy the line



     cout<<message<<endl;

inside the main function like that:

int main(int argc, char* argv[])
{
	char* message="Hi There!";

Greeting gr;
gr.PrintMessage();

 

     cout<<message<<endl;

return 0; }

Compile and execute the code. Command prompt displays:

Hello World

Hi There!

"Hello World" is output of gr.PrintMessage() line and "Hi there" is ouput of cout<<message<<endl; line

If you comment line message="Hello World\n"; inside the class constructor compile the code and try to execute it, program crashed because no value assigned to pointer char* message inside the class

There is the complete code:


#include<iostream.h>

class Greeting
{

public:

void PrintMessage();

Greeting();


private:
char* message;
};


Greeting::Greeting()
{
message = "Hello World\n";
}


void Greeting::PrintMessage()
{
	     char* message="How are you?";

        cout<<message<<endl;
}


int main(int argc, char* argv[])
{
	char* message="Hi There!";

Greeting gr;
gr.PrintMessage()'
return 0;
}<



 << PART I - Data Type
 << PART II - Pointers and Functions 



My eBooks on Amazon.com



Subscribe to our mail list to receive free code examples.

Comments

No comments yet.

Add Comment

* Required information
(never displayed)
 
Smile Sad Huh Laugh Mad Tongue Crying Grin Wink Scared Cool Sleep Blush Unsure Shocked
 
1000
Type the word for the number 9.
 
Enter answer:
Captcha
Refresh
 
Enter code:
 
Notify me of new comments via email.
 
Remember my form inputs on this computer.
 
I have read and understand the privacy policy. *
 
I have read and agree to the terms and conditions. *
 
 
Powered by Commentics