conversion constructors
play

Conversion Constructors Converting Objects class Money { ... - PowerPoint PPT Presentation

Conversion Constructors Converting Objects class Money { ... Money(); ... }; Money money; //1 int amt = 5; //2 money = amt; //3 How can we support this? Converting Objects class Money { ... Money(); Money(int amount); ... };


  1. Conversion Constructors

  2. Converting Objects class Money { ... Money(); ... }; Money money; //1 int amt = 5; //2 money = amt; //3 ● How can we support this?

  3. Converting Objects class Money { ... Money(); Money(int amount); ... }; Money money; //1 int amt = 5; //2 money = amt; //3 ● How can we support this? ● By adding a conversion constructor – Here the default constructor is issued for line 1 – Then in line 3, there is an implicit casting – This invokes the conversion constructor

  4. Converting Objects class Money { class Dollar ... { Money(); ... Money(int amount); Dollar(int dollars, int cents); Money(Dollar dollar); int Dollars(); Money(Gold gold); int Cents(); ... ... }; }; class Gold Money money; //1 { int amt = 5; //2 ... money = amt; //3 Gold(int grams); Dollar dollar(5, 50); //4 int Grams(); money = dollar; //5 ... Gold gold(10); //6 }; money = gold; //7 ● You can have up to one conversion constructors per source type ● This is because conversions constructors take exactly one parameter

  5. Implementation Money::Money() { amt = 0; } Money::Money(int amount) { amt = amount; } Money::Money(Dollar dollar) //not used { amt = (dollar.Dollars() * 100) + dollar.Cents(); } Money::Money(Gold Gold) //not used { amt = 4275 * gold.Grams(); }

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend