Loading lessons...
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:
| Notation | Example |
|---|---|
| C style | (double)total |
| C++ functional style | double(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.
| Cast | Purpose | Example |
|---|---|---|
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 sure | static_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 fails | dynamic_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 portable | reinterpret_cast<char*>(&n) |
#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:
static_cast: 4.25
functional: 4.25
Derived::hello
d2 is NULL
CONST CAST
first byte in memory: 68The 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
| Conversion | Example | Done in the | Using |
|---|---|---|---|
| Basic type → class type | Time t = 85; | destination class | a constructor with one argument |
| Class type → basic type | int m = t; | source class | a casting operator function operator int() |
| Class type → class type | Rupee r = d; | source class or destination class | a 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.
#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:
1 hr 25 min
3 hr 20 minA 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:
A casting operator function:
- must be a class member;
- must not specify a return type (the type name is the return type);
- must not have any arguments.
#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:
minutes = 150
hours = 2.5
minutes via cast = 1503.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
Ydefines a casting operatoroperator X(), or - the destination class
Xdefines a one-argument constructorX(Y y).
Only one of the two may be provided; providing both makes the conversion ambiguous.
| Conversion in the source class | Conversion in the destination class | |
|---|---|---|
| Function | casting operator operator Destination() | constructor Destination(Source) |
| Needs access to | the source's private data (it is a member) | the source's data through public getters |
| Defined in | the source class | the destination class |
#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:
12 dollars = Rs 996
50 euros = $55
as double = 554. 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.
#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:
length = 20Key points to remember
- Explicit casts:
(double)x(C style) ordouble(x)(functional); preferstatic_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.
explicitstops a constructor from being used for silent conversions.
📝 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
Timeconstructor example, theoperator int()example with its three rules, and theDollar/Rupee/Europrogram. - 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_castandreinterpret_cast. - Q4. What is the use of the
explicitkeyword? (2.5 Marks) - Q5. Differentiate between implicit and explicit type conversion. (2.5 Marks)