Re: What is the correct way to derive a class in regard to overloaded operators
kanze wrote:
olanglois@sympatico.ca wrote:
[snip]
4- Added the assignment opertor=(const Base &) (otherwise a
temporary Derived object is created...)
You also need to make the destructor of Base virtual. I'd also
add a private operator new[] to Derived -- in no case can you
allow the construction of C style arrays of Derived on the heap
(since they will fatally end up assigned to a Base*).
Yeah, but...
if sizeof(Base)==sizeof(Derived), and if ~Derived() has an empty
body (i.e. it does nothing but call ~Base()), then there isn't
likely to be a problem, not even with new Derived[] -- is there?
Yes, I am aware that it violates the standard... but show me a
program that does this, and a compiler that makes it crash?
#include <iostream>
#include <ostream>
struct Base {
int x;
// whatever...
Base(int z=0) : x(z) {}
~Base() { std::cout << "Destroy: " << x << '\n'; }
};
struct Derived : public Base { // No Multiple Inheritance
static int nextX;
Derived() : Base(nextX++) {}
// No new non-static data members
//~Derived(); -- Does not explicitly define the destructor
};
int Derived::nextX = 100;
int main() {
{
Base a(10);
Base *b = new Derived[5];
delete[] b; // Deleting with wrong data type, violates
standard...
// but is it EVER a problem in these limited situations?
// Calls ~Base() directly, instead of going through
~Derived()...
// But all ~Derived() does is forward to ~Base(), right?
}
std::cout << "Fin" << std::endl;
}
Even Comeau doesn't complain about this code
(haven't tried running it with Comeau, though)
I did try it with Microsoft, it gave the obvious results.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]