fork(4) download
  1. #include <iostream>
  2.  
  3. class Example {
  4. private:
  5. int a;
  6. // lots of important variables that live on the heap
  7. public:
  8. int getA() { return a; }
  9.  
  10. Example(Example& other) {
  11. std::cout << "Example copy constructor" << std::endl;
  12. a = other.a;
  13. }
  14.  
  15. Example(int a_local) {
  16. a = a_local;
  17. std::cout << "Example constructor" << std::endl;
  18. /* allocating memory, etc. ... */
  19. }
  20. };
  21.  
  22. class Child: public Example {
  23. // we get `a` and `getA()` from example
  24. private:
  25. int b;
  26. public:
  27. Child(int a2, int b2) : Example(a2) {
  28. std::cout << "Child constructor" << std::endl;
  29. b = b2;
  30. }
  31.  
  32. int getB() { return b; }
  33. int getAplusB() { return getA() + b; } // we can't use `a` directly since it's private
  34. };
  35.  
  36. int main() {
  37. Child c(1, 5);
  38. std::cout << c.getA() << std::endl;
  39. std::cout << c.getB() << std::endl;
  40. std::cout << c.getAplusB() << "\n" << std::endl;
  41.  
  42. Example& e = dynamic_cast<Example&>(c);
  43. // Example& e = c;
  44. // Example e = c;
  45. std::cout << e.getA() << "\n" << std::endl;
  46.  
  47. // Example e2(10);
  48. // Child c2 = dynamic_cast<Child&>(e2);
  49. }
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
Example constructor
Child constructor
1
5
6

1