class

#include<iostream>
using namespace std;
class A{
public:
char* s;
A(char* P):s(P) { }
};

int main(){
A* a1=new A("object1");
A* a2=new A("object2");
delete a1;
cout<<a2->s;
cout<<endl;
system("pause");
return 0;
}

I run this programm and the result is object 2; can you explain me this code line by line, thank you
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>    // Include library
using namespace std;  // Use standard name space
class A{             // Class object named a
public:            // Public (could have just made this a struct)
char* s;          // Contains a C-style string, named S
A(char* P):s(P) { } // Constructor, assigned whatever passed in to "s"
};  // End of class

int main(){  // Start of main
A* a1=new A("object1"); // Create class called a1 on heap. s set to "object1"
A* a2=new A("object2"); // Create class called a2 on heap. s set to "object2"
delete a1; // Delete memory allocated for a1
cout<<a2->s; // Print out contents of "s" from a2 ("object2")
cout<<endl; // Print new line, flush buffers
system("pause");  // System pause, assuming halt of program so it doesn't close
return 0; // Return 0, common for success
}


There's a glaring memory leak. Anything allocated with new should be deallocated with delete. In this case, it's the a2 object.
Last edited on
thank you so so much :) you are very helpful
Topic archived. No new replies allowed.