Thread: Deciphering a constructor.

  1. #1
    Registered User
    Join Date
    Sep 2015
    Posts
    22

    Deciphering a constructor.

    Hello,

    I'm trying to get started with c++ by modifying some code from a K&P book that parses CSV data via cin, to read the data from a file. I am having great difficulty understanding the class constructor as it is implemented:

    Code:
    Csv(istream& fin = cin, string sep = ",") : fin(fin), fieldsep(sep) {}
    I thought it would be as straightforward as replacing cin by a filepath but it doesn't work. I don't understand what the code after the colon is doing, especially fin(fin). The variables are defined as private:

    Code:
      private:
        istream& fin;           // Input file pointer.
        string line;            // Input line.
        vector<string> field;   // Field strings.
        int nfield;             // Number of fields.
        string fieldsep;        // Separator characters.
    Could someone please break this constructor down and explain it. I have not seen this type of constructor anywhere else.

    Thanks

  2. #2
    Registered User
    Join Date
    Jun 2017
    Posts
    157
    The code behind the colon is called member initializer list.
    Constructors and member initializer lists - cppreference.com

    It also could be written like:
    Code:
    Csv(istream& fin = cin, string sep = ",")
    {
      this->fin = fin;
      fieldsep = sep;
    }

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    I thought it would be as straightforward as replacing cin by a filepath but it doesn't work.
    You probably shouldn't be playing with the class definition, just call the constructor with the proper values.

    Code:
        // It is probably being called like:
        // Csv from_console;
    
        // To use a file you will need to pass an open file description to the constructor along with the delimiter you want to use.
        ifstream from_file("Your_csv_file_name");
        if(!from_file)
        {
            // Take some action if the file failed to open.
        }
    
        // Create an instance of Csv using the from_file stream and a comma as the delimiter. 
        Csv file(from_file, ',');

  4. #4
    Registered User
    Join Date
    Sep 2015
    Posts
    22
    Awesome thanks for both of those comments, OldGuy2 & jimblumberg.

    @OldGuy2, I still don't quite get
    Code:
    this->fin = fin;
    How can this even be? It looks like a paradox!

    Also @jimblumberg, I can't create an instance that way. The original code was...

    Code:
    string line;
    Csv csv;
    
    while (csv.getline(line) != 0)
    {
        Some stuff.
    }
    My attempt at using your suggestion is ...
    Code:
    std::ifstream from_file(FILE_PATH); // FILE_PATH is a macro.
    while (csv.getline(line) != 0)
    {
        Some stuff.
    }
    Csv file(from_file, FILE_DELIM);    // FILE_DELIM is a macro.
    That last line is causing problems(no matching function call).

    I've added the fstream library. I'm still missing something.

    Even so, I at least have some direction now so many thanks to you both.
    Last edited by SqueezyPeas; 03-23-2018 at 02:36 AM. Reason: Need some specific help.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > How can this even be? It looks like a paradox!
    The LHS is your member variable.
    The RHS is your parameter.
    If your member variable had a different name, the compiler would figure it out by itself.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Jun 2017
    Posts
    157
    Don't try to translate c to C++. They are total different languages.
    A simple demo how to read a file line by line
    Code:
    #include <iostream>
    #include <string>
    #include <cstdlib> // perror, errno
    #include <fstream>
    
    int main()
    {
      const std::string filename = "FileName"; 
      std::ifstream src(filename); // src(filename.c_str()) for oldeer compiler; 
    
      if (!src.good())
      {
        perror("Can't open file");
        return errno;
      }
      std::string line;
      while (std::getline(src, line)) // read's either till '\n' oe end of stream
      {
        // use line
      }
    }

  7. #7
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    That last line is causing problems(no matching function call).

    I've added the fstream library. I'm still missing something.

    Even so, I at least have some direction now so many thanks to you both.
    You'll need to post more content, a small complete program would be best. Also if you're getting error messages you need to post the complete error message, all of them, exactly as they appear in your development environment.

    By the way I changed the name of the instance in my snippet you'll need to use the proper names not just cut and past my snippet.

    Lastly why the "MACROS"? They should be avoided in C++ programs, prefer const qualified variables instead.

  8. #8
    Registered User
    Join Date
    Sep 2015
    Posts
    22
    Quote Originally Posted by OldGuy2 View Post
    Don't try to translate c to C++. They are total different languages.
    A simple demo how to read a file line by line
    Thanks again. I've abandoned trying to adapt that example and managed to implement a solution using the Boost Tokenizer. I understand your code, and it is essentially how I read each line in. There was just too much in that K&P example that I couldn't understand fully enough. I didn't want to use Boost but at least I have understood the examples from the library.

    Regards

  9. #9
    Registered User
    Join Date
    Sep 2015
    Posts
    22
    Quote Originally Posted by jimblumberg View Post
    Lastly why the "MACROS"? They should be avoided in C++ programs, prefer const qualified variables instead.
    I've converted the macros to const vars and read-up on the pros and cons. Thanks for the tip.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Deciphering a code example, string class confusion
    By bulletbutter in forum C++ Programming
    Replies: 3
    Last Post: 03-16-2018, 07:35 AM
  2. Need help deciphering a line
    By Polaris84 in forum C Programming
    Replies: 2
    Last Post: 09-08-2015, 09:27 AM
  3. Replies: 14
    Last Post: 07-02-2012, 10:21 AM
  4. Unbounded deciphering delay
    By Rob4226 in forum C Programming
    Replies: 0
    Last Post: 10-18-2009, 09:15 PM
  5. help deciphering code
    By tlovaj in forum C Programming
    Replies: 1
    Last Post: 03-10-2008, 09:48 PM

Tags for this Thread