virtual_method_self.carbon 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. //
  5. // AUTOUPDATE
  6. // RUN: %{explorer-run}
  7. // RUN: %{explorer-run-trace}
  8. // CHECK:STDOUT: c.Foo(): 1
  9. // CHECK:STDOUT: d.Foo(): 2
  10. // CHECK:STDOUT: e.Foo(): 3
  11. // CHECK:STDOUT: (*dp).Foo(): 3
  12. // CHECK:STDOUT: (*dc).Foo(): 3
  13. // CHECK:STDOUT: result: 0
  14. package ExplorerTest api;
  15. base class C {
  16. var value_c: i32;
  17. virtual fn Foo[self: Self]() -> i32 {
  18. return self.value_c;
  19. }
  20. }
  21. base class D extends C {
  22. var value_d: i32;
  23. // TODO: This should instead use `impl` when supported
  24. virtual fn Foo[self: Self]() -> i32 {
  25. return self.value_d;
  26. }
  27. }
  28. class E extends D {
  29. var value_e: i32;
  30. // TODO: This should instead use `impl` when supported
  31. virtual fn Foo[self: Self]() -> i32 {
  32. return self.value_e;
  33. }
  34. }
  35. fn Main() -> i32 {
  36. var c: C = {.value_c = 1};
  37. Print("c.Foo(): {0}", c.Foo());
  38. var d: D = {.value_d = 2, .base = {.value_c = 1}};
  39. Print("d.Foo(): {0}", d.Foo());
  40. var e: E = {.value_e = 3, .base={.value_d = 2, .base = {.value_c = 1}}};
  41. Print("e.Foo(): {0}", e.Foo());
  42. var dp: D* = &e;
  43. Print("(*dp).Foo(): {0}", (*dp).Foo());
  44. var dc: C* = &e;
  45. Print("(*dc).Foo(): {0}", (*dc).Foo());
  46. return 0;
  47. }