code_junkie

Default parameters with C++ constructors

Nov 11th, 2011
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. // Use this...
  2. class foo
  3. {
  4. private:
  5. std::string name_;
  6. unsigned int age_;
  7. public:
  8. foo(const std::string& name = "", const unsigned int age = 0) :
  9. name_(name),
  10. age_(age)
  11. {
  12. ...
  13. }
  14. };
  15.  
  16. // Or this?
  17. class foo
  18. {
  19. private:
  20. std::string name_;
  21. unsigned int age_;
  22. public:
  23. foo() :
  24. name_(""),
  25. age_(0)
  26. {
  27. }
  28.  
  29. foo(const std::string& name, const unsigned int age) :
  30. name_(name),
  31. age_(age)
  32. {
  33. ...
  34. }
  35. };
  36.  
  37. foo f1;
  38. foo f2("Name", 30);
  39.  
  40. class Vehicle {
  41. public:
  42. Vehicle(int wheels, std::string name = "Mini");
  43. };
  44.  
  45. Vehicle x = 5; // this compiles just fine... did you really want it to?
  46.  
  47. class Thingy2
  48. {
  49. public:
  50. enum Color{red,gree,blue};
  51. Thingy2();
  52.  
  53. Thingy2 & color(Color);
  54. Color color()const;
  55.  
  56. Thingy2 & length(double);
  57. double length()const;
  58. Thingy2 & width(double);
  59. double width()const;
  60. Thingy2 & height(double);
  61. double height()const;
  62.  
  63. Thingy2 & rotationX(double);
  64. double rotationX()const;
  65. Thingy2 & rotatationY(double);
  66. double rotatationY()const;
  67. Thingy2 & rotationZ(double);
  68. double rotationZ()const;
  69. }
  70.  
  71. main()
  72. {
  73. // gets default rotations
  74. Thingy2 * foo=new Thingy2().color(ret)
  75. .length(1).width(4).height(9)
  76. // gets default color and sizes
  77. Thingy2 * bar=new Thingy2()
  78. .rotationX(0.0).rotationY(PI),rotationZ(0.5*PI);
  79. // everything specified.
  80. Thingy2 * thing=new Thingy2().color(ret)
  81. .length(1).width(4).height(9)
  82. .rotationX(0.0).rotationY(PI),rotationZ(0.5*PI);
  83. }
  84.  
  85. // Header
  86. void doSomething(int i = 25) ;
  87.  
  88. // Source
  89. void doSomething(int i)
  90. {
  91. // Do something with i
  92. }
  93.  
  94. // Header
  95. void doSomething() ;
  96. void doSomething(int i) ;
  97.  
  98. // Source
  99.  
  100. void doSomething()
  101. {
  102. doSomething(25) ;
  103. }
  104.  
  105. void doSomething(int i)
  106. {
  107. // Do something with i
  108. }
  109.  
  110. foo bar[400];
  111.  
  112. foo bar("david", 34)[400]; // NOPE
Add Comment
Please, Sign In to add comment