I woud like to ask what is the difference between this
Tv *television = new Tv();
and
Tv television = Tv();
I woud like to ask what is the difference between this
Tv *television = new Tv();
and
Tv television = Tv();
The first one creates a dynamically allocated Tv
and binds it to a pointer to Tv
. The duration of the Tv
object is under your control: you decide when to destroy it by calling delete
on it.
new Tv(); // creates dynamically allocated Tv and returns pointer to it
Tv* television; // creates a pointer to Tv that points to nothing useful
Tv* tv1 = new Tv(); // creates dynamicalls allocated Tv, pointer tv1 points to it.
delete tv1; // destroy the object and deallocate memory used by it.
The second one creates an automatically allocated Tv
by copy initialization. The duration of the Tv
object is automatic. It gets destroyed deterministically, according to the rules of the language, e.g. on exiting scope:
{
// copy-initializaiton: RHS is value initialized temporary.
Tv television = Tv();
} // television is destroyed here.
"exiting scope" may also refer to the end of the life of an object of a class that contains a Tv
object:
struct Foo {
Tv tv;
}
....
{
Foo f;
} // f is destroyed, and f.tv with it.