[Discuss] SemiOT - Question for the C++ gurus

John Vetterli jvetterli at linux.ca
Mon Mar 5 08:53:36 PST 2007


On Sun, 4 Mar 2007, Adam Parkin wrote:
> How does one indicate in a constructor a default initialization for a 
> std::vector object?  Like what I want is in my default constructor for my 
> class (which takes a vector as an argument) to initialize a private member 
> vector to be empty if one isn't supplied to the constructor.  Or in code:
> class SomeClass
> {
> public:
>    // what goes in the ????? spot?
>    SomeClass (std::vector<string> vecIn = ?????) : privVec (vecIn);
> private:
>    std::vector<std::string> privVec;
> };

If you don't like the static dummy array that pw suggested, you can try this:

class SomeClass
{
public:
   SomeClass (std::vector<std::string> vecIn = std::vector<std::string>())
     : privVec (vecIn) { };
private:
   std::vector<std::string> privVec;
};


I would even suggest declaring the parameter to be a reference type to avoid 
an extra copy:

class SomeClass
{
public:
   SomeClass (const std::vector<std::string>& vecIn
               = std::vector<std::string>())
     : privVec (vecIn) { };
private:
   std::vector<std::string> privVec;
};


> SomeClass Foo ();            // Foo.privVec initialized with empty vector

No, this declares a function named "Foo" that takes no parameters and returns 
a "SomeClass" object.  You want:

SomeClass Foo;


HTH
JV


More information about the Discuss mailing list