tags:

views:

273

answers:

4

Is there a way to destruct a structure (not a class)?

+14  A: 

In C++ a struct is exactly the same as a class with the exception of the default visibility on members and bases. So if there is a way to "destruct" a class, you can use the exact same way to "destruct" a structure.

So, if you have a struct s { } in your C++ program you can do this:

s *v = new s();
delete v; // will call structure's destructor.
Pablo Santa Cruz
Or just letting an object fall out of scope will call the destructor.
Martin York
@Martin: yes. true.
Pablo Santa Cruz
@Martin: but letting an object pointer fall out of scope does not. It's important to make the distinction. In this example it's a pointer.
Mark Ransom
@Mark: Indeed. If you created the object with `new`, you destroy it with `delete` or, if you're wise, assign it to a smart pointer to take care of that for you. If you created the object automatically, you let it fall out of scope automatically. And if you invoked the primordial power of placement new to forge the object from raw bits, then you invoke the destructor to cast it back to the abyss whence it came - but usually you don't want to do that.
Mike Seymour
+5  A: 

Except for the default access specifier ("private" for class, "public" for struct), everything else is same in C++ class and struct. So, YES, you can write and use destructors in struct in the same way that is done in class.

ArunSaha
+4  A: 

Structs are identical to classes except the default visibility and inheritance are public (rather than private).

So you can create and destroy structs just like this (the same as a class, or built in type):

// Create on the heap, need to manually delete.
MyStruct *const pStruct = new MyStruct();
delete pStruct;

// Created on the stack, automatically deleted for you.
MyStruct struct;
Mark Ingram
A: 

Structs and classes are the same thing, there is just a technical difference (the default field of access) witch dues to a conceptual difference between the two. However every struct like a class call its constructors when the objects have to be created, and its destructor when its visibility field ends.

In C++ structs aren't less powerfull than classes.

Charlie