-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathconvert_class_to_primitive.cpp
More file actions
72 lines (61 loc) · 2.07 KB
/
convert_class_to_primitive.cpp
File metadata and controls
72 lines (61 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*******************************************************************************
*
* Program: Convert User-Defined Class Type To Primitive Type
*
* Description: Demonstration of how to convert a user-defined class type to
* a primitive type (like double, char, etc.) in C++.
*
* YouTube Lesson: https://www.youtube.com/watch?v=zRZLwzoQ1Fo
*
* Author: Kevin Browne @ https://portfoliocourses.com
*
*******************************************************************************/
#include <iostream>
using namespace std;
// create a simple Grade class
class Grade
{
// Grade objects will have a single member variable grade intended to be set
// to values like 92.45, 45.35, etc.
private:
double grade;
public:
// constructor for initializing the grade member variable
Grade(double grade) : grade(grade) {}
// operator type() allows us to create a function that will return a value
// of the specified type, defining how object instances will be converted to
// the type.
//
// In this case we define how to convert a Grade object to a double value by
// simply return the grade member variable's value...
operator double()
{
return grade;
}
// In the chase of converting a Grade object to a char, we return a "letter
// grade" A,B,C,D or F depending on the range of the grade value
operator char()
{
if (grade >= 80) return 'A';
else if (grade >= 70) return 'B';
else if (grade >= 60) return 'C';
else if (grade >= 50) return 'D';
else return 'F';
}
};
int main()
{
// instantiate a Grade object
Grade grade1(93.22);
// assigning the Grade object instance to a double variable will cause the
// type converstion to occur as we specified with operator, resulting in the
// value 93.22
double dbl_grade1 = grade1;
cout << "dbl_grade1: " << dbl_grade1 << endl;
// assigning the Grade object instance to a char variable will cause the
// type conversion to occur as we specified with operator, resulting in the
// value 'A'
char chr_grade1 = grade1;
cout << "chr_grade1: " << chr_grade1 << endl;
return 0;
}