Thursday, July 30, 2009

[Cpp-Programming] Re: doubt in c++

Good explanation M.J :-)

On Thu, Jul 30, 2009 at 11:08 PM, Mohammad-Javad Izadi <m.j.izadi@gmail.com> wrote:

Hi,


They're not the same.


The first one (without the new operator) is static. First of all, this means that it is not dependent on the run-time state of the program. Secondly, the object is created on the stack. This means that in the end of the scope (mostly when the function returns), the object is destroyed (its destructor is called). But with new operator, the object is created on the heap dynamically. In this case the object is not bound to any scope, and therefore, you have to destroy it manually (with delete operator).


The dynamic schema is useful when the creation of an object depends on the run-time state of the program. For example you can have an if-statement, and if the condition holds, create an object, and if it does not, do not create it. This can be done with new, but not with static object creation.


A good example is a dynamic array of objects, i.e. when you do not know in advance how many objects you are going to have.


You can use this code:

    cin >> n;

    Square* sq = new Square[n];


But not with static creation:

    cin >> n;

    Square sq[n];


Here the compiler gives you an error (well, gcc might not give an error, but according to standard c++, it should), because if you create some object statically, it should be clear at compile time, how much space it needs on the memory. Here, the amount of memory needed is dependent on "n" which can't be known until run-time.


I hope this helps!


Regards,

--

MJ


cooldude wrote:

hi,  i'm pretty new to c++. i have got a simple doubt. please answer.  i have a class called square.  class square { //some implementation here }  now when i write the main program i create the object. here is where i'm confused. i feel i can create the object square in two ways. let me know if i'm correct.  square obj_sqr1; // this is one way  square* ptr_square; ptr_square = new square ; //  using the new operator, forgive me if the syntax is wrong  what is the difference between the two ? are they same ? ..     




--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "C++ Programming" group.
To post to this group, send email to Cpp-Programming@googlegroups.com
To unsubscribe from this group, send email to Cpp-Programming+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/Cpp-Programming?hl=en
-~----------~----~----~----~------~----~------~--~---

0 Comments:

Post a Comment

<< Home