Is it possible to delete a non dynamic variable?
Or is it automatically deleted when I construct a new one with the same name?

int N;
int N;

Is this possible?

My purpose is, that I want to use an object from a class in a loop:

for(;;)
{
  myobj = myclass(param1,param2);
}

but the class hasnt got an empty constructor: myclass();
Therefore I cannot write:

mycass myobj;
for(;;)
{
  myobj = myclass(param1,param2);
}

Can you use the following?

myclass *myobjptr;
for(;;)
{
  myobjptr = new myclass(param1,param2);


  //Code

   delete myobjptr;
}

This is not really a good way of doing things as it might result in heap fragmentation due to the frequent allocation and deletes of memory involved.

In a loop like this

int main()
{
    for(int ix = 0; ix<5; ix++)
    {
        MyObject obj = MyObject(ix);
    }
}

obj is constructed and destricted on every loop iteration. Put cout statements in the constructor and destructor if you wish to confirm it.

Any non-dynamic variable is deleted at the end of it's scope.

mycass myobj;
for(;;)
{
  myobj = [B]myclass(param1,param2);[/B]
}

The bolded object is deleted just before the compiler reaches the next line. It's scope spans just until the end of that assignment.

Just for emphasis, an automatic variable is deleted with it reaches
the end of its block. So for example :

int main(){
  {
      int x = 0;
   } //x is deleted when it reaches this bracket
  
    int x = 3, y = 3
} //x and y is deleted when it reaches this bracket

so as you see, you can use "{ ... }" the bracket to destroy the variable.
But you should try to give each variable unique name and not have to
do that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.