Want more features on Pastebin? Sign Up, it's FREE!
Guest

c++ call constructor from constructor

By: a guest on Feb 28th, 2012  |  syntax: None  |  size: 1.18 KB  |  views: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. class Test {
  2.     public Test() {
  3.         DoSomething();
  4.     }
  5.  
  6.     public Test(int count) : this() {
  7.         DoSomethingWithCount(count);
  8.     }
  9.  
  10.     public Test(int count, string name) : this(count) {
  11.         DoSomethingWithName(name);
  12.     }
  13. }
  14.        
  15. class Foo {
  16.  public:
  17.    Foo(char x, int y=0);  // combines two constructors (char) and (char, int)
  18.    ...
  19.  };
  20.        
  21. class Foo {
  22.  public:
  23.    Foo(char x);
  24.    Foo(char x, int y);
  25.    ...
  26.  private:
  27.    void init(char x, int y);
  28.  };
  29.  
  30.  Foo::Foo(char x)
  31.  {
  32.    init(x, int(x) + 7);
  33.    ...
  34.  }
  35.  
  36.  Foo::Foo(char x, int y)
  37.  {
  38.    init(x, y);
  39.    ...
  40.  }
  41.  
  42.  void Foo::init(char x, int y)
  43.  {
  44.    ...
  45.  }
  46.        
  47. class Foo {
  48. public:
  49.   Foo(char x, int y) {}
  50.   Foo(int y) : Foo('a', y) {}
  51. };
  52.        
  53. class SomeType
  54. {
  55.   int number;
  56.  
  57. public:
  58.   SomeType(int newNumber) : number(newNumber) {}
  59.   SomeType() : SomeType(42) {}
  60. };
  61.        
  62. class Foo() {
  63.     Foo() { /* default constructor deliciousness */ }
  64.     Foo(Bar myParam) {
  65.       new (this) Foo();
  66.       /* bar your param all night long */
  67.     }
  68. };
  69.        
  70. class Foo  {
  71.      int d;        
  72. public:
  73.     Foo  (int i) : d(i) {}
  74.     Foo  () : Foo(42) {} //new to c++11
  75. };
  76.        
  77. class Foo  {
  78.      int d = 5;        
  79. public:
  80.     Foo  (int i) : d(i) {}
  81. };
clone this paste RAW Paste Data