code_junkie

Virtual functions in constructors, why do languages differ?

Nov 10th, 2011
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. class base {
  2. public:
  3. base()
  4. {
  5. std::cout << "foo is " << foo() << std::endl;
  6. }
  7. virtual int foo() { return 42; }
  8. };
  9.  
  10. class derived : public foo {
  11. int* ptr_;
  12. public:
  13. derived(int i) : ptr_(new int(i*i)) { }
  14. // The following cannot be called before derived::derived due to how C++ behaves,
  15. // if it was possible... Kaboom!
  16. virtual int foo() { return *ptr_; }
  17. };
  18.  
  19. type
  20. TComponent = class
  21. public
  22. constructor Create(AOwner: TComponent); virtual; // virtual constructor
  23. end;
  24.  
  25. TMyEdit = class(TComponent)
  26. public
  27. constructor Create(AOwner: TComponent); override; // override virtual constructor
  28. end;
  29.  
  30. TMyButton = class(TComponent)
  31. public
  32. constructor Create(AOwner: TComponent); override; // override virtual constructor
  33. end;
  34.  
  35. TComponentClass = class of TComponent;
  36.  
  37. function CreateAComponent(ComponentClass: TComponentClass; AOwner: TComponent): TComponent;
  38. begin
  39. Result := ComponentClass.Create(AOwner);
  40. end;
  41.  
  42. var
  43. MyEdit: TMyEdit;
  44. MyButton: TMyButton;
  45. begin
  46. MyEdit := CreateAComponent(TMyEdit, Form) as TMyEdit;
  47. MyButton := CreateAComponent(TMyButton, Form) as TMyButton;
  48. end;
Add Comment
Please, Sign In to add comment