Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 File IO
Index -> Programming, C++ -> C++ Help
Goto page Previous  1, 2
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: Mon May 30, 2005 4:01 pm   Post subject: (No subject)

Ah, I left out one thing. Rather than the assignment style of construction, you should use the initialization style, as shown in the following modification of the previous code.

A recap:

c++:
class name
{
   private:
      std::string first;
      std::string last;
   public:
      name(std::string f, std::string l)
      {
         first = f;
         last = l;
      }

      std::string full_name() const
      {
         return first + " " + last;
      }
};

int main()
{
   const name bob("Bob", "Smith");
   
   std::cout << bob.full_name() << std::endl;

   return 0;
}


Now, remember how I said things should be constant unless otherwise required? Well, let's say that our name should have constant first and last names. It cannot be changed, under any circumstances.

c++:
class name
{
   private:
      const std::string first;
      const std::string last;
   public:
      name(std::string f, std::string l)
      {
         first = f;
         last = l;
      }

      std::string full_name() const
      {
         return first + " " + last;
      }
};

int main()
{
   const name bob("Bob", "Smith");
   
   std::cout << bob.full_name() << std::endl;

   return 0;
}


Now, when we call the constructor those two strings get initialized by default to empty strings. Since they're constant, we can't assign to them after initialization, so this fails. Instead we directly initialize them.

c++:
class name
{
   private:
      const std::string first;
      const std::string last;
   public:
      name(std::string f, std::string l) : first(f), last(l) { }

      std::string full_name() const
      {
         return first + " " + last;
      }
};

int main()
{
   const name bob("Bob", "Smith");
   
   std::cout << bob.full_name() << std::endl;

   return 0;
}
Sponsor
Sponsor
Sponsor
sponsor
MysticVegeta




PostPosted: Mon May 30, 2005 4:57 pm   Post subject: (No subject)

Wow, i wonder if you type at 1000WPM or you already have tuts typed out (which i smarter thing i guess) Or if you are like a super nerd who breathes programming (no offense)

Anyways, Really good job man 9 examples. whew Wink
Thanks a lot
Display posts from previous:   
   Index -> Programming, C++ -> C++ Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 2 of 2  [ 17 Posts ]
Goto page Previous  1, 2
Jump to:   


Style:  
Search: