CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Feb 2003
    Location
    London, UK
    Posts
    23

    Question valid type for default arguement of a vector in a constructor

    Hi,

    I have a constructor for class Grapher that is defined like this:


    Grapher( const vector<string> & , string ="graph");

    The thing is i would like to provide arguement for the vector<string> so that I have a default constructor e.g.

    Grapher temp();

    Anything I put in means gcc kicks up a fuss.

    Any ideas?

    Thanks

    Daniel Brewer

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449
    Why not create a default constructor and pass an empty (or whatever) vector<string> of your choice? You will need to separate the code into another function, but it will do the job.
    Code:
    #include <vector>
    #include <string>
    
    typedef std::vector<std::string> VecString;
    
    class Grapher
    {
        public:
            Grapher( const VecString& vs, std::string s ="graph")
            {
                   InitFunc(vs, s);
            }
    
            Grapher( ) 
            { 
                VecString S; 
                InitFunc(S);
            }  
    
        protected:
            void InitFunc( const VecString& vs, std::string s="graph")
            { /* Place the body of the non-default constructor here */ }
    };
    Just another tip: If Grapher is defined in a header file, it looks like you used a "using namespace std" in your header file for Grapher since I see a lack of "std::" within the fle. It isn't a good idea to introduce the namespace in the header file. When you include the header in a CPP file, you are introducing the entire std:: within the CPP also, which may not be desired (the .CPP file may have a "vector" or "string" class that is different than std::vector or std::string. Your header file would mess things up).

    Instead do what I did above -- explicitly state "std::" in the header file. Within the .CPP file, you can state "using namespace std:".

    Regards,

    Paul McKenzie

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured