ya_zay4eg

//45_MemberInitializers

Jun 26th, 2014
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. //45_MemberInitializers
  2.  
  3. #include "SimpleClass.h"
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. SimpleClass myObject (404, 808);
  10. myObject.print();
  11. }
  12.  
  13. //------------------------------------------------------------------------------------
  14.  
  15. #ifndef SIMPLECLASS_H
  16. #define SIMPLECLASS_H
  17.  
  18.  
  19. class SimpleClass
  20. {
  21.     public:
  22.         SimpleClass(int a, int b);//constructor that takes two values
  23.                                   //assign one to a reg variable and
  24.                                   //one to a constant variable  
  25.         void print ();//function to print it out
  26.     protected:
  27.     private:
  28.         int regVar;
  29.         const int constVar;
  30. };
  31.  
  32. #endif // SIMPLECLASS_H
  33.  
  34. //------------------------------------------------------------------------------------
  35. #include "SimpleClass.h"
  36. #include <iostream>
  37. using namespace std;
  38. //constant members need member syntax to be initialized
  39.  
  40. SimpleClass::SimpleClass(int a, int b) //
  41. : regVar (a), //here is the special syntax (begins with ':') !!!member initialize syntax!!!
  42.   constVar(b)//and it lays between ')' and '{' !!!don't put ';' after
  43. {
  44.     /*
  45.     you don't write any of your code when initializing variables in curly braces
  46.     */
  47. }
  48. void SimpleClass::print(){//i forgot to place '::' for the first time
  49. cout<<"Reg_var is: "<<regVar<<" and const var is "<<constVar<<endl;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment