Skip to content

Commit 40e11f3

Browse files
Explicit keyword usage
1 parent 9735400 commit 40e11f3

File tree

4 files changed

+72
-0
lines changed

4 files changed

+72
-0
lines changed

basics_using_cpp.pro

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,6 @@ CONFIG -= app_bundle
44
CONFIG -= qt
55

66
DISTFILES += *.md
7+
8+
SUBDIRS += \
9+
keyword_explicit

keyword_explicit/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# keyword_explicit
2+
Understanding of ***explicit*** keyword behaviour in cpp prog.
3+
4+
In general if a class has a constructor which can be called with a single argument, then this constructor becomes conversion constructor because such a constructor allows conversion of the single argument to the class being constructed.
5+
6+
We can make the constructor explicit(doesn't allow implicit conversions) with the help of ***explicit*** keyword.
7+
8+
To get clear understanding [click here!](https://stackoverflow.com/a/31351956/5903276).

keyword_explicit/keyword_explicit.pro

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
TEMPLATE = app
2+
CONFIG += console c++11
3+
CONFIG -= app_bundle
4+
CONFIG -= qt
5+
6+
SOURCES += main.cpp
7+
8+
DISTFILES += *.md \
9+
README.md

keyword_explicit/main.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include <iostream>
2+
#include <string>
3+
4+
using namespace std;
5+
6+
class Price
7+
{
8+
public:
9+
Price(double amount = 0.00) : m_amount(amount) {}
10+
11+
void print() {
12+
cout << "My price: " << m_amount << endl;
13+
}
14+
15+
private:
16+
double m_amount;
17+
};
18+
19+
20+
class PriceExplicit
21+
{
22+
public:
23+
explicit PriceExplicit(double amount = 0.00) : m_amount(amount) {}
24+
25+
void print() {
26+
cout << "My price: " << m_amount << endl;
27+
}
28+
29+
private:
30+
double m_amount;
31+
};
32+
33+
34+
int main()
35+
{
36+
cout << "!!! Keyword explicit !!!\n" << endl;
37+
38+
39+
// No need to typecast
40+
Price pr = 8.00;
41+
pr.print();
42+
43+
44+
// Typecast must needed here or else it ill throw compilation err as below
45+
// "error: conversion from ‘double’ to non-scalar type ‘PriceExplicit’ requested"
46+
// Uncomment below line and expect same error stated above
47+
// PriceExplicit prExp = 8.00;
48+
PriceExplicit prExp = (PriceExplicit)8.00;
49+
prExp.print();
50+
51+
return 0;
52+
}

0 commit comments

Comments
 (0)