FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
cpp-coding-exercise/virtual-interface/main.cpp at main · DoctorLai/cpp-coding-exercise · GitHub
DoctorLai
/
cpp-coding-exercise
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
3
Star
3
Code
Issues
0
Pull requests
1
Discussions
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cpp-coding-exercise
/
virtual-interface
/
main.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
59 lines (49 loc) · 1.08 KB
Breadcrumbs
cpp-coding-exercise
/
virtual-interface
/
main.cpp
Copy path
File metadata and controls
59 lines (49 loc) · 1.08 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
*
This example shows the interface using virtual functions in C++.
*/
#
include
<
iostream
>
#
include
<
memory
>
class
Shape
{
public:
virtual
double
area
()
const
=
0
;
//
Pure virtual function
virtual
~Shape
() {}
//
Virtual destructor
};
class
Circle
:
public
Shape
{
private:
double
radius;
public:
Circle
(
double
r) : radius(r) {}
double
area
()
const
override
{
return
3.14159
* radius * radius;
}
};
class
Rectangle
:
public
Shape
{
private:
double
width, height;
public:
Rectangle
(
double
w,
double
h) : width(w), height(h) {}
double
area
()
const
override
{
return
width * height;
}
};
int
main
()
{
std::unique_ptr<Shape> shapes[
2
];
shapes[
0
] = std::make_unique<Circle>(
5.0
);
shapes[
1
] = std::make_unique<Rectangle>(
4.0
,
6.0
);
//
The following line would cause a compilation error because Shape is an abstract class
//
Shape a = new Shape();
for
(
int
i =
0
; i <
2
; ++i) {
std::cout <<
"
Area of shape
"
<< i +
1
<<
"
:
"
<< shapes[i]->
area
() << std::endl;
}
return
0
;
}
Back
|
FazBrowse Home
|
New Git URL