Script Kitty
Script Kitty

Reputation: 1747

Create and destroy an object in a loop

I am new to C++/stacko and want to principally:

  1. Create an object
  2. Read in an enormous amount of data for that
  3. After calculating that object's score, print it out
  4. Delete the object from memory because each object has a lot of variables attributed to it
  5. Loop it 1000 times

It seems simple enough but after looking around I see things about destructors but I don't know if that's what I am looking for.

for(int i=0; i<1000; i++){
    applicants object1;
    object1.readin();
    cout<<object1.calculate();
    //How do I delete object1 and start again?
}

Thank you so much for any help. I don't know hardly anything about this language. Also, do I even need objects? I'm confused

Upvotes: 1

Views: 3909

Answers (3)

You don't need to call the destructor of object1, it would be called at the end of the loop body.

Technically, destructors are called at the end (right brace) of the block declaring the object.

This is why the right brace } is sometimes jokingly called the most important statement in C++. A lot of things may happen at that time.

It is however generally considered bad style to do real computations in constructors or destructors. You want them to "allocate" and "deallocate" resources. Read more about RAII and the rule of five (or of three).

BTW, if an exception happens, the destructors between the throw and the matching catch are also triggered.

Please learn more about C++ containers. You probably want your applicants class to use some. Maybe it should contain a field of some std::vector type.

Also learn C++11 (or C++14), not some older version of the standard. So use a recent compiler (e.g. GCC 4.9 at least, as g++, or Clang/LLVM 3.5 at least, as clang++) with the -std=c++11 option (don't forget to enable warnings with -Wall -Wextra, debugging info with -g for debugging with gdb, but enable optimizations e.g. with -O2 at least, when benchmarking). Modern C++11 (or C++14) has several very important features (missing in previous standards) that are tremendously useful when programming in C++. You probably should also use make (here I explain why), see e.g. this and others examples. See also valgrind.

Upvotes: 3

Rob
Rob

Reputation: 1974

It is not necessary to delete object1.

For every iteration of the loop, a new object object1 will be created (using default constructor) and destructed after the "cout" statement.

Upvotes: 4

marsh
marsh

Reputation: 2720

Object one will be deleted automatically when it goes out of scope at the end bracket. You are already doing it. Be wary as if you create a pointer it will not be destructed when it goes out of scope. But your current code is working fine.

http://www.tutorialspoint.com/cplusplus/cpp_variable_scope.htm

Upvotes: 2

Related Questions