Advertisement
bhok

C++ Classes, constructors, memberwise

Sep 23rd, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. // More C++ Tutorial at BrandonHok.com
  2.  
  3. #include <iostream>
  4.  
  5. // Classes, constructors, memberwise assignment
  6.  
  7. class FireBurning
  8. {
  9.    
  10. public:
  11.     // This is the default constructor, similar to a prototype with
  12.     // return types. This sets up basic outline of an object.
  13.     // By default, the FireBurning temperature will be 500 celsius and 100 meters long.
  14.     // Constructors generally must have the same name as the class name
  15.     FireBurning(int celsius = 500, int meters = 100);
  16.    
  17.     // This is the first function or action that you want your class to have/do
  18.     void fireShot();
  19. private:
  20.     // These are data variables that you want the class to have.
  21.     // It is good practice to label private variables with '_' at the end of its name.
  22.     int celsius_;
  23.     int meters_;
  24. };
  25.  
  26. // Class name :: Constructor (same name as class name)
  27. FireBurning::FireBurning(int c, int m)
  28. {
  29.     // This allows to set/intializes our variables to our object. You will see below.
  30.     celsius_ = c;
  31.     meters_ = m;
  32. }
  33.  
  34. // Class name :: member function
  35. void FireBurning::fireShot()
  36. {
  37.     // This is your function. Design it the same as a function.
  38.     std::cout << "How hot? Celsius = " << celsius_ << std::endl;
  39.     std::cout << "How many meters? "    << meters_ << std::endl;
  40. }
  41.  
  42. int main()
  43. {
  44.     // Declare your first object
  45.     // Classname objectname
  46.     FireBurning firstFire;
  47.  
  48.     // Declare your second object and set the arguments. Remember the constructor?
  49.     FireBurning secondFire(300, 200);
  50.  
  51.     // Now we can command the objects with our member functions that we assigned it.
  52.     // Test them out!!
  53.     // Use the objectname . memberfunction ;
  54.     // dot notation is the .
  55.     firstFire.fireShot();
  56.     secondFire.fireShot();
  57.  
  58.     std::cout << "Our next line of shots!\n";
  59.     // What happens here? All the variables are transferred to the left object!
  60.     // The "=" represents the default memberwise assignment
  61.     secondFire = firstFire;
  62.     secondFire.fireShot();
  63.  
  64.  
  65.     system("pause");
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement