tags:

views:

72

answers:

3

I have a basic_iostream derived class like this:

class MyStream : public std::basic_iostream< char >, 
                 private boost::noncopyable
{
public:
    explicit MyStream( SomeUsefulData& data ) : 
        buffer_( data ),
        std::basic_iostream< char >( &buffer_ )
    {
    };

    ~MyStream()
    {
    };

private:
    /// internal stream buffer
   MyStreamBuffer< char > buffer_;
}; // class MyStream

When I create an instance of it, though, I get a DataAbort exception.

SomeUsefulData data;
MyStream stream( data );  // <- Data Abort

If, however I change MyStream to heap allocate the MyStreamBuffer, it works fine:

class MyStream : public std::basic_iostream< char >, 
                 private boost::noncopyable
{
public:
    explicit MyStream( SomeUsefulData& data ) : 
        std::basic_iostream< char >( new MyStreamBuffer< char >( data ) )
    {
    };

    ~MyStream()
    {
        delete rdbuf();
    };
}; // class MyStream

Is it wrong to use a class member to initialize a parent class?

Thanks, PaulH

+6  A: 

Direct base classes are always initialised first, no matter what order you put the initialisation statements in. If you turn on more compiler warnings, you should get a warning about this.

Which means that yes, it is wrong to initialise a base class with a member, sorry!

Autopulated
+2  A: 

Yes it's wrong.

The order of initialization is:

  1. Base class objects (if present)
  2. Member data objects
  3. Constructor function code

So this :

explicit MyStream( SomeUsefulData& data ) : 
    buffer_( data ),
    std::basic_iostream< char >( &buffer_ )

Actually means that:

explicit MyStream( SomeUsefulData& data ) : 
    std::basic_iostream< char >( &buffer_ ),
    buffer_( data )
Samuel_xL
A: 

its wrong Rememebr that the base class is constructed first and then the derived class

here

explicit MyStream( SomeUsefulData& data ) : 
        ...
        std::basic_iostream< char >( &buffer_ )
    {
    };

you try to init the base class with buffer_ that isn't yet constructed

jojo