
- Forum
- Programming Talk
- C and C++
- Doubt with Scope
Doubt with Scope
This is a discussion on Doubt with Scope within the C and C++ forums, part of the Programming Talk category; I have my C++ program as below: int main() { sample s1; test t1 = s1.example(); cout << "t1.a = ...
-
Doubt with Scope
I have my C++ program as below:
int main()
{
sample s1;
test t1 = s1.example();
cout << "t1.a = "<< t1.a << endl;
cout << "t1.b = "<< t1.b << endl;
};
struct test
{
int a;
int b;
};
struct sample
{
test example()
{
test t;
t.a = 100;
t.b = 200;
return t;
}
};
I have a doubt in the above C++ program. I want to know the scope of availability of the object test that is created inside the function example(). Will it get lost once the method gets completed? Kindly clarify my doubt.
-
06-08-2007, 05:56 PM #2
- Join Date
- Jun 2007
- Answers
- 3
yes t gets created when the control reaches the function
and destroyed when control exits from the function.but the value is safely returned to the main.returning a locally created refrence variable is unsafe.
in this example u must declare struct test and struct samplebefore main in order to tell the main function that u have created test and sample somwhere in the program
-
Yes as in Java in C++ also the scope gets lost as you have asked. Can you guess what happens if you make &t at the end instead of t. Try out or guess and tell me.
-
12-26-2010, 02:20 AM #4
- Join Date
- Dec 2010
- Answers
- 32
well...here you are using the concept of nested structure....and you are creating a local object or reference of the structure...so definitely it will lost its scope after the method is completed.
-
Sponsored Ads

Reply With Quote





