Reputation: 3820
Say I have two classes like so:
controller.hpp (included by controller.cpp)
#include "testing.hpp"
class controller
{
public:
testing _testing; // call constructor
}
testing.hpp
class testing
{
public:
testing();
~testing();
}
How do I call the destructor of testing
and re-construct it from controller.cpp? Thank you.
Upvotes: 0
Views: 479
Reputation: 2383
In your code a controller
owns a testing
. The implication to anyone reading the code is that it is the same testing
for the lifetime of the controller
. This is certainly also how C++ see it - it will construct the testing
during construction of a controller
and destroy the testing
when the controller
is destroyed.
Two possible solutions:
testing
, reset it. This is what @LogicStuff was talking about in his comment on your question. _testing = testing();
constructs a new testing
and then copies its state to the existing instance, making the exisiting instance look like a new one. You could (should?) make this explicit by giving testing
a Reset
method (whose implementation should typically be that assignment *this = testing();
rather than a hand-coded resetting of each member variable.) - Do this only if resetting a testing
makes business sense.testing
doesn't make sense on a business level, and you are in fact wanting to replace it, then have controller
own a std::unique_ptr<testing>
instead. Then you can reset
or swap
a newly constructed instance in whenever you need to and still be sure that destructors will be called automatically.Upvotes: 1
Reputation: 4019
You usually don't explicitly call the destructor. It is call automatically when the object is destroyed. When an object is created on the stack, the destructor is called automatically when the object goes out of scope. When an object is created on the heap (by new'ing it), the destructor is called automatically when delete is called on the object.
Upvotes: 2
Reputation: 62553
I think, you totally misunderstand the idea of default constructors. The main idea is that you almost never call default constructor explicitly (absent placement new). Ditto for destructors. So in your case, testing
constructor will be called automatically whenever controller
object is created, and it it's destructor will be called whenever controller
object is destroyed.
Upvotes: 2