+ 5
What is a scope??
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
+ 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
}
??
+ 5
Got it
+ 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
+ 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.
+ 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/
+ 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/
+ 1
Shahil Ahmed yes there are 2 scopes for x in ur example.
+ 1
You will find that it print x and after that object of enclosing class dies and so nested class object.