mul. inheritance & overloading operator new/delete solved by virtual base inheritance?

C

cppsks

Hello. I posted a question regarding this yesterday. I came up with the
following solution but I am a little hesistant as to this solution having
any side-effects that I am not aware of. The solution seems to work though.
Please let me know if this is okay or if I need to modify something here.
Thanks !!!!

Here is what I have:

#include <new>
#include <iostream>
#include "stdlib.h"

class Base
{
public:
Base() { cout << "Base:" << this << endl; }
void* operator new(size_t size) throw (std::bad_alloc) { cout << "operator
Base::new(size:" << size << ")\n"; return malloc(size); }
void operator delete(void* ptr) throw() { cout << "operator
Base::delete(ptr:" << ptr << ")\n"; free(ptr); }
};

class Base1 : public virtual Base
{
public:
Base1() { cout << "Base1:" << this << endl; }
};

class Base2 : public virtual Base
{
public:
Base2() { cout << "Base2:" << this << endl; }
};

class SubClass : public Base1, public Base2
{
public:
SubClass() { cout << "SubClass:" << this << endl; }
};

class SubClass1 : public Base2, public Base1
{
public:
SubClass1() { cout << "SubClass1:" << this << endl; }
};


int main()
{
cout << "\n===================\n";
Base1* hi = new SubClass;
delete hi;
cout << "\n===================\n";
hi = new SubClass1;
delete hi;
cout << "\n===================\n";
}


Here is the output:

===================
operator Base::new(size:12)
Base:0x3d0d8
Base1:0x3d0d0
Base2:0x3d0d4
SubClass:0x3d0d0
operator Base::delete(ptr:0x3d0d0)

===================
operator Base::new(size:12)
Base:0x3d0d8
Base2:0x3d0d0
Base1:0x3d0d4
SubClass1:0x3d0d0
operator Base::delete(ptr:0x3d0d4)

===================
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top