oop - Why C++ new is not returning pointer to the object it creates? -
I understood the following code, according to my knowledge when I declare new use of something new, then this particular Creates an object of type and gives the indicator on that object. But here when I use a new student object, it does not return pointer to the object. Also, when I do not make any type of conversion from student to student, instead of giving an error, new student (s1) " student (student *) " Call me P>
#include & lt; bits / stdc ++ H & gt; using namespace std; Class student {public: cool; Student (student * s) {// is taking it for constructor indicator, while I am calling it under this value - & gt; Cool = s-> Quiet; } Student () {it-> Calm = 1; }}; Zero blah (student) {printf ("cold:% d \ n", S. col); } Int main () {student s1 = new student (); // New student is not returning here * s1.cool = 2; Student S2 = New Student (S1); // Here we are passing S1, which type of students are, but why is the producer (student *) called ??? Blah (s2); } The following output is that I am without any error:
Good: 2
Students (student * s) You are leaking memory.
/ code>
The conversion is used to fully satisfy, because this is not explicit marked here: What happens here:
student s1 = new student (); Do you pull a new student object? The expression new expression evaluates an indicator when the compiler sees the assignment, then it recognizes that the assignment will not work because s1 a student And you are assigning a student * to do this so it looks around to change it and I look for the constructor mentioned above.
So what you are doing is equivalent:
student s1 = student (new student ()); Since you do not always mark delete , the heap allocation is leaked, but otherwise your program works properly from your perspective.
If you mark the conversion constructor in this way:
Clear student (student * s) Then compiler this The creator will not use it automatically for conversions, it is necessary to specify some kind of sound, and line student s1 = new student (); In reality, there will be a compile time error, while allowing the student to s1 = student (new student ()); to work (but of course it would still be the cause of a memory leak).
Comments
Post a Comment