Thread: Question about scope...

  1. #1
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547

    Question about scope...

    Working through "Thinking in c++"... and yes I think I'm understanding it this time, thanks to everyone's help, the other day.

    One thing is not terribly clear...

    Code:
    void Fred (int x)
     { // a bunch of code
        if (x = 3)
          { Foo bar(31);    // class
           // calls to bar
          }                       <--- is bar destroyed here?
       // a bunch more code
      }                           <---or here?
    And ... can I do this to control bar's lifetime?

    Code:
    void Fred (int x)
     { // a bunch of code
       { Foo bar(31);    // class
         // calls to bar
       }                       
       // a bunch more code
      }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    The scope always ends at the matching closing brace of the opening brace containing the object in question.

    And yes, you can create scopes just by having open/close braces in the middle of the code. It's the syntactic equivalent of
    Code:
    void Fred (int x)
     { // a bunch of code
       if ( 1 ) { Foo bar(31);    // class
         // calls to bar
       }                       
       // a bunch more code
      }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    -bleh-
    Join Date
    Aug 2010
    Location
    somewhere in this universe
    Posts
    463
    Just for practicing purposes, you can write the destructor that print some message so that when your class goes out of scope you can see your class's destructor called.
    "All that we see or seem
    Is but a dream within a dream." - Poe

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Thanks guys. Much appreciated.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. xy was not declared in this scope: compiler error!
    By twilight in forum C++ Programming
    Replies: 41
    Last Post: 08-13-2009, 12:33 PM
  2. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  3. Scope Related question
    By csonx_p in forum C++ Programming
    Replies: 13
    Last Post: 08-24-2008, 11:02 AM
  4. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  5. Design layer question
    By mdoland in forum C# Programming
    Replies: 0
    Last Post: 10-19-2007, 04:22 AM