Lesson 21 +35 XP

Explicit Type Conversions & Conversions Involving Classes

Explicit Type Conversions & Conversions Involving Classes

The compiler converts between built-in types automatically (Lesson 7), but it knows nothing about our classes. How should a Time object become a number of minutes, or an int become a Distance? This lesson covers explicit conversion (casting) between built-in types, the four C++ cast operators, and the three kinds of conversion involving classes: basic to class, class to basic, and class to class.

1. Explicit Conversion of Built-in Types

An explicit conversion (a cast) is a conversion the programmer asks for. C++ supports the C notation and adds a functional notation:

NotationExample
C style(double)total
C++ functional styledouble(total)

The functional style looks like a function call (and like a constructor call, which is exactly how class conversions work). It cannot be used with type names of more than one word, such as unsigned int(x); use a typedef or the C style for those.

2. The C++ Cast Operators

C-style casts are blunt: one notation does everything, from harmless to dangerous, and they are hard to search for in code. Standard C++ adds four named cast operators, each for one purpose.

CastPurposeExample
static_cast<T>(e)ordinary, well-defined conversions checked at compile time: numeric types, void* to a typed pointer, base to derived pointer when you are surestatic_cast<double>(total)
dynamic_cast<T>(e)safe downcasting in a polymorphic hierarchy, checked at run time; gives NULL (pointers) or throws bad_cast (references) if it failsdynamic_cast<Circle*>(shapePtr)
const_cast<T>(e)adds or removes const (or volatile)const_cast<char*>(text)
reinterpret_cast<T>(e)low-level reinterpretation of bits: pointer to integer, unrelated pointer types; not portablereinterpret_cast<char*>(&n)
C++
#include <iostream>
using namespace std;

class Base {
public:
    virtual ~Base() {}
};
class Derived : public Base {
public:
    void hello() {
        cout << "Derived::hello" << endl;
    }
};

void printUpper(char* s) { // an old function that is not const-correct
    for (int i = 0; s[i] != '\0'; i++) {
        if (s[i] >= 'a' && s[i] <= 'z') {
            cout << char(s[i] - 32);
        } else {
            cout << s[i];
        }
    }
    cout << endl;
}

int main() {
    int total = 17, count = 4;
    cout << "static_cast:  " << static_cast<double>(total) / count << endl;
    cout << "functional:   " << double(total) / count << endl;

    Base* b1 = new Derived;
    Base* b2 = new Base;
    Derived* d1 = dynamic_cast<Derived*>(b1); // succeeds: b1 points to a Derived
    Derived* d2 = dynamic_cast<Derived*>(b2); // fails: b2 points to a Base
    if (d1) {
        d1->hello();
    }
    cout << "d2 is " << (d2 ? "valid" : "NULL") << endl;

    char buffer[] = "const cast";
    const char* msg = buffer;
    printUpper(const_cast<char*>(msg)); // remove const to call the old function

    int n = 0x41424344;
    unsigned char* bytes = reinterpret_cast<unsigned char*>(&n);
    cout << "first byte in memory: " << int(bytes[0]) << endl;

    delete b1;
    delete b2;
    return 0;
}

Output:

OUTPUT
static_cast:  4.25
functional:   4.25
Derived::hello
d2 is NULL
CONST CAST
first byte in memory: 68

The last line is 68 (0x44) because Intel processors store the least significant byte first (little-endian); a big-endian machine would print 65.

3. Conversions Involving Classes

ConversionExampleDone in theUsing
Basic type → class typeTime t = 85;destination classa constructor with one argument
Class type → basic typeint m = t;source classa casting operator function operator int()
Class type → class typeRupee r = d;source class or destination classa casting operator in the source, or a constructor in the destination

3.1 Basic type to class type: a constructor

A constructor that takes one argument of a basic type converts that type into the class. It is called automatically in assignments and initialisations.

C++
#include <iostream>
using namespace std;

class Time {
    int hrs, mins;

public:
    Time() {
        hrs = 0;
        mins = 0;
    }
    Time(int duration) { // conversion constructor: int -> Time
        hrs = duration / 60;
        mins = duration % 60;
    }
    void show() {
        cout << hrs << " hr " << mins << " min" << endl;
    }
};

int main() {
    Time t1 = 85; // int converted to Time by the constructor
    Time t2;
    t2 = 200; // also converts: a temporary Time(200) is assigned
    t1.show();
    t2.show();
    return 0;
}

Output:

OUTPUT
1 hr 25 min
3 hr 20 min

A char* to String constructor, String(const char* s), is another classic example: String s = "hello";.

3.2 Class type to basic type: a casting operator function

Constructors cannot convert from a class to a basic type, because the basic type has no constructor we can write. Instead, the source class defines an overloaded casting operator:

texttt{operator} typename() { dots }

A casting operator function:

  1. must be a class member;
  2. must not specify a return type (the type name is the return type);
  3. must not have any arguments.
C++
#include <iostream>
using namespace std;

class Time {
    int hrs, mins;

public:
    Time(int h, int m) {
        hrs = h;
        mins = m;
    }
    operator int() {
        return hrs * 60 + mins;
    } // Time -> int (minutes)
    operator double() {
        return hrs + mins / 60.0;
    } // Time -> double (hours)
};

int main() {
    Time t(2, 30);
    int minutes = t;  // calls operator int()
    double hours = t; // calls operator double()
    cout << "minutes = " << minutes << endl;
    cout << "hours   = " << hours << endl;
    cout << "minutes via cast = " << int(t) << endl;
    return 0;
}

Output:

OUTPUT
minutes = 150
hours   = 2.5
minutes via cast = 150

3.3 One class type to another

Suppose obj_x = obj_y; where obj_x is of class X (destination) and obj_y is of class Y (source). Either:

  • the source class Y defines a casting operator operator X(), or
  • the destination class X defines a one-argument constructor X(Y y).

Only one of the two may be provided; providing both makes the conversion ambiguous.

Conversion in the source classConversion in the destination class
Functioncasting operator operator Destination()constructor Destination(Source)
Needs access tothe source's private data (it is a member)the source's data through public getters
Defined inthe source classthe destination class
C++
#include <iostream>
using namespace std;

class Dollar; // forward declaration

class Rupee {
    double amount;

public:
    Rupee(double a = 0) {
        amount = a;
    }
    Rupee(const Dollar& d); // destination-class conversion: Dollar -> Rupee
    void show() {
        cout << "Rs " << amount << endl;
    }
};

class Dollar {
    double amount;

public:
    Dollar(double a = 0) {
        amount = a;
    }
    double getAmount() const {
        return amount;
    }
    operator double() const {
        return amount;
    } // Dollar -> double
    void show() {
        cout << "$" << amount << endl;
    }
};

Rupee::Rupee(const Dollar& d) {
    amount = d.getAmount() * 83; // uses only the public interface of Dollar
}

class Euro {
    double amount;

public:
    Euro(double a) {
        amount = a;
    }
    operator Dollar() const { // source-class conversion: Euro -> Dollar
        return Dollar(amount * 1.1);
    }
};

int main() {
    Dollar d = 12;
    Rupee r = d; // constructor Rupee(const Dollar&)
    cout << "12 dollars = ";
    r.show();

    Euro e(50);
    Dollar d2 = e; // casting operator Euro::operator Dollar()
    cout << "50 euros   = ";
    d2.show();

    double plain = d2; // class -> basic
    cout << "as double  = " << plain << endl;
    return 0;
}

Output:

OUTPUT
12 dollars = Rs 996
50 euros   = $55
as double  = 55

4. Preventing Unwanted Conversions: explicit

A one-argument constructor converts silently, which can hide mistakes: with Array(int size), the line Array a = 10; compiles and makes an array of 10 elements, which may not be what the writer meant. Marking the constructor explicit allows only direct, visible calls.

C++
#include <iostream>
using namespace std;

class Array {
    int size;

public:
    explicit Array(int n) {
        size = n;
    }
    int length() {
        return size;
    }
};

int main() {
    Array a(10); // OK: direct call
    // Array b = 10;        // error: the constructor is explicit
    // a = 20;              // error: no implicit int -> Array conversion
    a = Array(20); // OK: the conversion is written out
    cout << "length = " << a.length() << endl;
    return 0;
}

Output:

OUTPUT
length = 20
💡 Tip

Key points to remember

  • Explicit casts: (double)x (C style) or double(x) (functional); prefer static_cast, dynamic_cast, const_cast, reinterpret_cast.
  • Basic → class: a one-argument constructor (Time t = 85;).
  • Class → basic: a casting operator operator int(): a member, no return type, no arguments.
  • Class → class: casting operator in the source or constructor in the destination, not both.
  • explicit stops a constructor from being used for silent conversions.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Explain the three types of conversion involving classes with programs. (10 Marks)
  • Write: the three-row table, the Time constructor example, the operator int() example with its three rules, and the Dollar/Rupee/Euro program.
  • Q2. What is a casting operator function? State its rules. (5 Marks)
  • Q3. Explain the four C++ cast operators with examples. (5 Marks)
  • Write: the table and the program with static_cast, dynamic_cast, const_cast and reinterpret_cast.
  • Q4. What is the use of the explicit keyword? (2.5 Marks)
  • Q5. Differentiate between implicit and explicit type conversion. (2.5 Marks)