Exforsys
+ Reply to Thread
Results 1 to 4 of 4

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 = ...

  1. #1
    rachelle is offline Member Array
    Join Date
    Apr 2006
    Answers
    97

    Exclamation 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.


  2. #2
    tarungosain20 is offline Junior Member Array
    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


  3. #3
    ashlee is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    108
    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.


  4. #4
    Manyamanas is offline Member Array
    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



Latest Article

Network Security Risk Assessment and Measurement

Read More...