Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can we apply new like in the example below with a simple object?

C++
class x
{
    public:
         x()
         {
             cout<<"Default constructor";
         }
         ~x()
         {
             cout<<"Destructor called";
         }
};

int main()
{
    x o = new x();
    getch();
    return 0;
}
Posted
Updated 6-Nov-11 3:38am
v3
Comments
Manfred Rudolf Bihy 6-Nov-11 9:37am    
Please wrap your code in pre tags next time.

NO.
new x()

returns an x* (a pointer to an x object) that points-to the newly created object.

the correct way to to that is
int main()
{
   //creates a new default-constructed x, giving its
   //address back to px
   x* px = new x(); 
  
   //calls x::~x() on the object pointed by px,
   //and return teh memory to the system.
   delete px;
  
   //wait for a key (not hortodox, but may be needed)
   getch();
}


Alternativelly, you can instantiate an x object into the stack as a function local variable with

int main()
{
   x o; //create a default constructed x into the stack
   getch(); //wait for a kay
} //here o is destroyed.


Note that if you run this program, o will seem not destroyed, since its destruction happens after getch().
To see its real work, invoke it from an opened command prompt:
it will print
txt
Default constructor will wait for a keypress here
Destructor called


Note that you should also place an endl on the printed message, otherwise the message themselves could be not printed until an endl is found, that cout to be usedrequire the std namespace to be included, that cout requires <iostream>

So a complete sample can be

C++
#include <iostream>

class x
{
public:
     x()
     {
         std::cout<<"Default constructor"<<std::endl;
     }
     ~x()
     {
         std::cout<<"Destructor called"<<std::endl;
     }
};

// main woarking with dynamic memory

int main()
{
    x* o = new x();
    getch();
    delete o;
    return 0;
}

//alternative main, working on stack

int main()
{
    x o;
    getch();
    return 0;
}


use only one of the two variants of main.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 6-Nov-11 10:44am    
Sure, a 5.
I would add that in such simple cases stack is preferable, please see my comment to the solution by Chuck.
--SA
Albert Holguin 6-Nov-11 19:13pm    
+5, but agree with SA, stack should be used whenever possible... the performance difference is tremendous.
Emilio Garavaglia 7-Nov-11 2:55am    
The question was about the new operator. My reference to the stack was just because the user did not intentionally (looks like a user coming from C# or Java: he uses pointers every time without knowing it!)
Albert Holguin 7-Nov-11 11:29am    
Even if the question is about the new operator, it would've been worth mentioning to him that his usage in the example is not necessary.
Since the program doesn't compile, there is no use for "new". The compiler complains : error C2440: 'initializing' : cannot convert from 'x *' to 'x'

You declare an object "o" of type x. That's enough to instantiate the class. Then you use "new" to instantiate another object of the class.

Now what you cannot do is store the reference to the object (result of "new") into a variable that is of the class and not a pointer to the class. "x *o = new x();" would be the proper way to do this.

So, either declare a variable of the class:

x o;

or declare a pointer to the class and create the instance with new:

x *o = new x();

but don't mix them
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 6-Nov-11 10:42am    
Sure, a 5. I would also add: as C++ gives an opportunity to choose between value semantics vs reference semantic, heap should not be overused. In many cases, using stack-only class instances is quite enough. Instances on heap are needed more for dynamically created structures as linked lists, queues, hash tables, sets, associative containers and a lot more.
--SA
Albert Holguin 6-Nov-11 19:15pm    
This explanation is incomplete with no mention of delete or stack/heap difference. 3
Chuck O'Toole 6-Nov-11 19:20pm    
But the question was "What's the use of new operator in c++?" I do not usually answer questions that are not asked nor guess at what questions might potentially be asked. Besides, as written, it didn't compile but if he used his original "x o" instantiation, no delete was needed (nor was new)
Albert Holguin 6-Nov-11 21:14pm    
If the question is about using new, I think mentioning delete is pretty much a given, specially when talking to a new user.
Chuck O'Toole 6-Nov-11 19:25pm    
Besides, mine is "solution 2". "Solution 1" already launched into a fine discussion on new/delete and/or malloc/free. Do we really need every solution to duplicate the others in content?
The simple answer is yes.
You have a memory leak however. You are allocating the object o, but not releasing its memory.
C++
int main()
{
    x o = new x();
    getch();
    delete o; //this will call ~x()
    return 0;
}


Now to answer the question in the topic.

new/delete has many uses.

Firstly dynamic memory allocation. All of this is exactly the same as the malloc/free functions:
When dealing with dynamic size data (for example the contents of a file) it is not practical to use the stack, because you have no idea how big the file will be.
C++
//This allocates 1KB on the stack to store the contents of the file.
//If the file is bigger than 1KB this is going to cause issues
char file_buffer[1024];
//instead you would use
int file_size = /*...*/; //get the size of the file somehow
char *file_buffer = new char[file_size];


Typically when dealing with large amounts of memory you would use the heap, with new/delete or malloc/free. Your program has limited (although usually quite large) stack space. If you run out of stack your program will crash abruptly. At least if you run out of heap malloc will return null or new will thrown an exception, both of which you can handle as needed.

Now for the differences in new/delete and malloc/free.
new calls the constructor, delete calls the destructor. malloc/free don't.

new automatically gets the correct data size when allocating.
C++
int *numbers = (int *)malloc(10 * sizeof(int));
//is the same as
int *numbers = new int[10];


When allocating an array with new, you must use delete[]
C++
int *numbers = new int[10];
delete[] numbers;
 
Share this answer
 
Comments
Chuck O'Toole 6-Nov-11 10:15am    
Andrew, I think you missed the missing "*". "o" is an instantiation itself, he cannot store the result of "new" into it nor can he call "delete" on it. The compiler complains bitterly. See my solution (done almost simultaneously with yours).
Andrew Brock 6-Nov-11 10:25am    
Oops. perhaps I should try running the code to see what the real issue is occasionally. 5'd your answer.
Chuck O'Toole 6-Nov-11 11:04am    
Thanks. I do note that the remainder of your explanation is quite good and worth its own 5.
Albert Holguin 6-Nov-11 19:11pm    
I hardly ever try running their code... don't worry about it... +4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900