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

conversion constructors
SMART_READER_LITE
LIVE PREVIEW

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); ... };


slide-1
SLIDE 1

Conversion Constructors

slide-2
SLIDE 2

Converting Objects

  • How can we support this?

class Money { ... Money(); ... }; Money money; //1 int amt = 5; //2 money = amt; //3

slide-3
SLIDE 3

Converting Objects

  • 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

class Money { ... Money(); Money(int amount); ... }; Money money; //1 int amt = 5; //2 money = amt; //3

slide-4
SLIDE 4

Converting Objects

  • You can have up to one conversion constructors per source type
  • This is because conversions constructors take exactly one

parameter

class Money { ... Money(); Money(int amount); Money(Dollar dollar); Money(Gold gold); ... }; Money money; //1 int amt = 5; //2 money = amt; //3 Dollar dollar(5, 50); //4 money = dollar; //5 Gold gold(10); //6 money = gold; //7 class Dollar { ... Dollar(int dollars, int cents); int Dollars(); int Cents(); ... }; class Gold { ... Gold(int grams); int Grams(); ... };

slide-5
SLIDE 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(); }