Is this snippet respectfully coded? I heard when using a virtual destructor should only be reccommended if your using polymorphism and or a derived class thats using virtual as well. As you can see I am using pure virtual functions. Am I doing this wrong?
If B is a subtype of A, and you ever delete an A * that may point to an instance of B, then A::~A() needs to be virtual, or some resources may not be properly released.
For example:
1 2 3
B *b = new B;
A *a = b;
delete a; // <- Incorrect if A::~A() is not virtual.
The most common reason for needing virtual destructors is to put polymorphic objects in a centralized container that owns their pointers:
1 2 3 4 5 6 7
std::vector<A *> v;
//...
for (auto p : v)
p->do_it();
//...
for (auto p : v)
delete p;
Ok helios, now I understand what you mean. Basically line 5 is invalid since I had setup the destructor as virtual, but if I did not set up a virtual destructor, line 5 would be valid... right?
Lumpkin, what do you mean create functions for the variables? I did make function(s), a float returnType that gets the computed addition of the pointer variables, and another function void that shows the result. Is that what you mean, or maybe somethibg else?
Basically line 5 is invalid since I had setup the destructor as virtual, but if I did not set up a virtual destructor, line 5 would be valid... right?
Line 5 is valid. A compiler won't reject it. It's incorrect because it may not properly release some resources.
But yes, making Math::~Math() virtual would make the code correct.
I am just practicing with pointers and learning new tricks. I know I do not have to use it for this purpose, but I want to understand more on using them and when is the best time to use them.