tags:

views:

317

answers:

3

Suppose I need to have a class which wraps a priority queue of other objects (meaning the queue is a member of the class), and additionally gives it some extra functions.

I am not quite sure what the best way is to define that vector and, mainly, how to instantiate it.

Currently I have something like this in the header file:

// in SomeClass.h:
class SomeClass
{
    public:
     SomeClass(); // constructor
            // other methods
    private:
     std::priority_queue<OtherClass> queue;
};

while the source file is something like this:

// in SomeClass.cpp
SomeClass::SomeClass():
    queue() // removed the constructor, no need to explicitly call it
    {}

// other methods


EDIT: removed the call, per Ray's answer.

+3  A: 

Just write:

SomeClass::SomeClass():
    queue() { }

C++ knows to call the constructor automatically from there with no arguments.

Ray Hidayat
+2  A: 

Your member is an instance, but what you're doing is trying to initialize that instance with a pointer to a newly allocated instance. Either leave the initialization empty (as Ray pointed out) or leave it out of the initialization list of the constructor completely.

SomeClass::SomeClass() {}

has the same queue initialized as

SomeClass::SomeClass() : queue() {}

If you really want to allocate it on the heap using new, then your member needs to be declared in the header as:

private:
            std::priority_queue<OtherClass>* queue;

But I would recommend against doing that, unless you plan to let some other class take over ownership of the same instance of queue later and don't want the destructor of SomeClass to free it.

Michel
A: 

Building on Michel's example, if you really want that pq allocated on heap you will be better off with

`boost::smart_ptr<std::priority_queue<OtherClass> > queue;`

or as a last resort if you don't have access to boost

`std::auto_ptr<std::priority_queue<OtherClass> > queue;`
Tanveer Badar