Thread: class reference function

  1. #1
    Registered User
    Join Date
    Jun 2008
    Posts
    106

    class reference function

    What does the reference operator do in this case:

    Code:
      const dataset_buf& read_data_set (const string& dataname) {
    How would I use this function? dataset_buf is another class, this function mentioned above is in the class "dataset_loader". It is supposed to return a reference to dataset_buf.

    Code:
    class dataset_loader {
    public:
      static void Init () { Exception::dontPrint(); }
      dataset_loader (const string& filename) : hdf5_file(filename, H5F_ACC_RDONLY), datasets() {}
      ~dataset_loader () {hdf5_file.close();   }
    
      const dataset_buf& read_data_set (const string& dataname) {
    Code:
    class dataset_buf{
    dataset_buf& operator= (const dataset_buf& other) { ...

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    It depends on what you want to do with the dataset_buf object that it returns a reference to. If you're going to call a single function on it, you can just chain the functions together:
    Code:
    my_dataset_loader.read_data_set(dataname).output_results();
    If you're going to be doing a lot of work with the dataset_buf and want to work on the exact instance that is returned, you'll want to create a reference variable to refer to that same instance:
    Code:
    dataset_buf& returned_dataset = my_dataset_loader.read_data_set(dataname);
    returned_dataset.do_some_work();
    returned_dataset.do_more_work();
    returned_dataset.output_results();
    If you want to use a copy of the results, (which may be unlikely since the function returns a reference on purpose) then make a normal, non-reference variable to save the return value. This will make a copy so any changes won't affect the original instance returned by the function:
    Code:
    dataset_buf returned_dataset = my_dataset_loader.read_data_set(dataname);
    returned_dataset.do_some_work();
    returned_dataset.do_more_work();
    returned_dataset.output_results();
    The copy might be expensive, so use the reference version unless you really want to avoid changing the original value.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  3. const at the end of a sub routine?
    By Kleid-0 in forum C++ Programming
    Replies: 14
    Last Post: 10-23-2005, 06:44 PM
  4. undefined reference to function in class error
    By bladerunner627 in forum C++ Programming
    Replies: 12
    Last Post: 10-18-2005, 09:06 AM
  5. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 06:51 PM