+ 5

What is a scope??

12th May 2018, 7:45 AM
Shahil Ahmed
Shahil Ahmed - avatar
9 odpowiedzi
+ 1
Actually it's destructed because test object dies as program finishes with main function. cause object is created with in main function only. If you add some more lines in code u will understand what I mean. here have example. https://code.sololearn.com/c2V91sZMhjD4/?ref=app
12th May 2018, 8:51 AM
Yugabdh
Yugabdh - avatar
+ 5
so this the stuff #include <iostream> using namespace std; class scope1{ public: int x; //here x is in a scope } int main(){ int x; //and now its in a different scope } ??
12th May 2018, 8:03 AM
Shahil Ahmed
Shahil Ahmed - avatar
+ 5
Got it
12th May 2018, 9:27 AM
Shahil Ahmed
Shahil Ahmed - avatar
+ 4
Final confirmation so in this code the obj is destructed bcz obj is getting out of scope from scope1?? https://code.sololearn.com/cf1yVc8Qbefz/?ref=app
12th May 2018, 8:19 AM
Shahil Ahmed
Shahil Ahmed - avatar
+ 2
scope is life of an variable. life in the sense where that variable exists. There are 2 scopes possible : 1.local 2.global local variables are not accessible outside of local block or local scope "{ }" this generally indicate block. While global variable can be accessed in any block using scope resolution operator "::" if there exist an local variable with same name or can be accessed directly.
12th May 2018, 8:03 AM
Yugabdh
Yugabdh - avatar
+ 2
Shahil Ahmed - Look this link up for code examples of c++ local and global variable scopes: https://www.codesdope.com/cpp-scope-of-variables/
12th May 2018, 8:07 AM
Rahul George
Rahul George - avatar
+ 1
" Scope of Variables in C++ In general, scope is defined as the extent upto which something can be worked with. In programming also scope of a variable is defined as the extent of the program code within which the variable can we accessed or declared or worked with. ... " Source: https://www.geeksforgeeks.org/scope-of-variables-in-c/
12th May 2018, 8:00 AM
Rahul George
Rahul George - avatar
+ 1
Shahil Ahmed yes there are 2 scopes for x in ur example.
12th May 2018, 8:09 AM
Yugabdh
Yugabdh - avatar
+ 1
You will find that it print x and after that object of enclosing class dies and so nested class object.
12th May 2018, 8:52 AM
Yugabdh
Yugabdh - avatar