Variable scope - Computer Programming For Beginners

+++++++

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 

Please rate the tutorial

1 2 3 4 5 6 7 8 9 10



Learn SQL Programming By Examples [Kindle Edition]2.99

Learn PHP Programming by Examples [Kindle Edition] $2.99

Learn Visual Basic 6.0 [Kindle Edition] $1.99

How to Build Your Own Web Site from Scratch [Kindle Edition] $1.49

New-trip.com website source code

Comments
 
Register to add comments ( 1000 char ) for variable_scope.php.