I verily know how to write classes and include some destructors,
Copy constructors etc. What am not very sure about is whether all classes
need a destructor ???? yeah that's the question
class dynamo
{
public:
dynamo ()=default;
~dynamo (); /// necessary
private;
int *dyn_ptr; /// will point to a dynamic array;
};
struct errors
{
errors (string& err);
~errors (); /// this i don't think so.
};
class errorlist
{
public:
errorlist ();
~errorlist ();/// I don't think this would be required too.
private:
vector<errors> vec_err (20);
}
what classes really need destructors?
only classes involving dynamic memory? or all classes?
All classes have destructors. If you do not write one, it will be generated automatically.
You need to write destructor yourself only when you have something to write inside.
In first example you need destructor, because you have to write delete[] manually.
In second and thired there is nothing to release manually, so you do not need to write one.
Another reason to writedestructor is if you need to make it virtual. If you do not have need to actually destriy anything, you can mark it as default: virtual ~foo() = default;
Bravo. this is precisely what I wanted to know write destructor yourself only when you have something to write inside. . Thank you so much @minnippa. virtual ~foo() = default; so I can also mark a destructor virtual even if
It might not be used as a base class??.( mean inheritance and polymophism).
Thanks now I fully understand but to use derived classes through base class pointer.
here do you mean like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class dynamo
{
public:
dynamo ()= default;
virtual ~dynamo ();
private:
int *dyn_ptr;
};
class bigdynamo: public dynamo
{
public:
bigdynamo ();/// to define
virtual ~dynamo (); //added yet another dynamic array;
private:
int *another_ptr;
};
class foo
{
public:
virtualvoid baz()
{ std::cout << "foo\n"; }
virtual ~foo() = default;
}
class bar: public foo
{
public:
virtualvoid baz()
{ std::cout << "bar\n"; }
virtual ~bar() = default; //Not actually needed in derived class
}
int main()
{
foo* x = new foo;
x -> baz();
delete x; //Everything is normal
x = new bar; //pointing to the derived class
x -> baz();
delete x; //Might do horrible things if foo destructor is not virtual
}