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

Discussion in 'C++' started by cppsks, Oct 27, 2004.

  1. cppsks

    cppsks Guest

    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)

    ===================
    cppsks, Oct 27, 2004
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jong Choi

    Matrix3d Mul function

    Jong Choi, Aug 6, 2003, in forum: Java
    Replies:
    0
    Views:
    484
    Jong Choi
    Aug 6, 2003
  2. HeroOfSpielburg
    Replies:
    1
    Views:
    380
    Alf P. Steinbach
    Aug 6, 2003
  3. cppsks
    Replies:
    2
    Views:
    1,270
    Markus Elfring
    Oct 27, 2004
  4. cppsks
    Replies:
    0
    Views:
    404
    cppsks
    Oct 27, 2004
  5. Gordon Schumacher

    SOLVED: Function overloading and base types

    Gordon Schumacher, Aug 26, 2006, in forum: C++
    Replies:
    0
    Views:
    308
    Gordon Schumacher
    Aug 26, 2006
Loading...

Share This Page