c++ - Scope of object created using new -


I am learning C ++ as a hobby and "new" to create a new object dynamically I'm wrestling. I have read that dynamically created classes do not scope, but this does not work for my simple example. When executed

, the value of 'testValue1' is set to 555 in the constructor and is printed. When the control is mainly returned, then 'testvalue' is unfortunately set to 0 (or not defined - not sure). I can set the value inside the main and the value is properly maintained for the main and also the loop properly.

Problem: I do not understand why the initial value of 555 is not why the control is back to the main. I know that for the right to the dynamically assigned class, I am confused or scarcity of understanding ... any help is appreciated. Here is the sample code:

  // main.cpp # include & lt; Iostream & gt; using namespace std; Square GeneralVerses {Private: Public: // Testing values ​​for data values ​​1; // Constructor General () {cout & lt; & Lt; "I'm in the General Wreck Constructor" & lt; & Lt; Endl; int testValue1 = 555; Cout & lt; & Lt; "TestValue1 has been defined" & lt; & Lt; TestValue1 & lt; & Lt; Endl; } ~ GeneralVerses (zero) {cout & lt; & Lt; "I'm in the normal war district" & lt; & Lt; Endl; }; }; Int main (int argc, char * argv []) {cout & lt; & Lt; "I'm in the Main" & lt; & Lt; Endl; Commonwealth * myGeneralVars = new general servers; // Create on Hep Kate & lt; & Lt; "Main 1 Testway 1 =" & lt; & Lt; MyGeneralVars- & gt; Test value 1 & lt; & Lt; Endl; MyGeneralVars-> testValue1 = 777; Cout & lt; & Lt; "Main 2 TestLove1 =" & lt; & Lt; MyGeneralVars- & gt; Test value 1 & lt; & Lt; Endl; {Cout & lt; for int i = 0; i & lt; = 3; i ++) & Lt; "Inside ..." & lt; & Lt; Endl; Cout & lt; & Lt; "Main 3" & lt; & Lt; I & lt; & Lt; "Testvalue1 =" & lt; & Lt; MyGeneralVars- & gt; Test value 1 & lt; & Lt; Endl; } delete myGeneralVars; // Deleting a pile return from 0; }   

This statement:

  int testValue1 = 555;   

A local variable , declares the data of the same name different from the member.

So this member.

Instead, for example

  testValue1 = 555;   

Use the manufacturer's memory initialization list, such as:

  General (): testValue1 (555) {cout & lt; & Lt; "I'm in the General Wreck Constructor" & lt; & Lt; Endl; Cout & lt; & Lt; "TestValue1 has been defined" & lt; & Lt; testValue1 & lt; & Lt; Endl; }    

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -