fork download
  1. #include <iostream>
  2.  
  3. namespace A {
  4. namespace B {
  5. struct C {
  6. struct D {
  7. int e; // variable e lifetime is same with struct D lifetime. Available only within struct D initialized
  8. D() : e(42) {}
  9. } d; // variable d lifetime is samw with C struct lifetime. Available only within struct C initialized
  10. C() {}
  11. C(int v) {
  12. d.e = v;
  13. }
  14. } c; // variable c lifetime is entire program. Scope is A::B::c
  15. }
  16. }
  17.  
  18. int main() {
  19. // access variable with program lifetime in A::B namespace
  20. std::cout << A::B::c.d.e << std::endl;
  21.  
  22. // create local variable of type A::B::C and access its fields
  23. A::B::C myc(55);
  24. std::cout << myc.d.e << std::endl;
  25.  
  26. // declare struct F within main function scope and access its fields
  27. struct F {
  28. int g;
  29. F(int v) : g(v) { }
  30. } f (100);
  31. std::cout << f.g << std::endl;
  32.  
  33. return 0;
  34. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
42
55
100