0% found this document useful (0 votes)
36 views89 pages

T3 Embedded Programing 07072022

The BGSV Embedded Academy (BEA) program aims to develop embedded competence through various training modules, including automotive basics, software development, and embedded programming. The curriculum covers essential programming principles, embedded system characteristics, and real-time operating systems, emphasizing the importance of C programming in embedded systems. The training includes classroom instruction, online self-learning, and practical demonstrations to enhance participants' skills in embedded software development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views89 pages

T3 Embedded Programing 07072022

The BGSV Embedded Academy (BEA) program aims to develop embedded competence through various training modules, including automotive basics, software development, and embedded programming. The curriculum covers essential programming principles, embedded system characteristics, and real-time operating systems, emphasizing the importance of C programming in embedded systems. The training includes classroom instruction, online self-learning, and practical demonstrations to enhance participants' skills in embedded software development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 89

BGSV Embedded Academy (BEA)

Focused Program to Develop Embedded Competence

BGSV EMBEDDED ACADEMY

T1: Automotive Basics


(Sensor, SW, Mobility P1: Requirements
M1: SW Development
Engineering
Technical
T2: Automotive
Solution) SW
Architecture
Methodological
Lifecycle Process
P2: Design Principles
Competence
(AUTOSAR)
T3: Embedded
Competence Competence
Programming P3: Review
M3: Clean Code
T5: Test Overview P4: Safety & Security

Classroom training, Online Self-learning, Live Demo


Purpose: Develop basic general embedded competence
Disclaimer

 This slide is a part of BGSV Embedded Academy (BEA) program and only
used for BEA training purposes.
 This slide is Bosch Global Software Technology Company Limited’s internal
property. All rights reserved, also regarding any disposal, exploitation,
reproduction, editing, distribution as well as in the event of applications for
industrial property rights.
 This slide has some copyright images and text, which belong to the
respective organizations.
T3
EMBEDDED
PROGRAMMING
Objectives &
Assumptions
Remind general programming principles
Remind key embedded system knowledges
How to program for embedded system effectively
Code optimization & Secure coding
Know and practice Object-oriented programming

Experienced with programming at basic


level
Not focus on how to programming
C and C++

5
Agenda

1. Programing principles remind


1. Programing remind/Overview
2. Language Evaluation Criteria
3. The Compiling Process
2. Embedded system programing
1. What is embedded system?
2. Which common elements inside Embedded SW?
3. Constraints affect design choices?
4. Why C is most common language for Embedded programing?
5. What skills required for Embedded programmer?
6. RTOS
3. Some importance topics that related to embedded programming
4. OOP principles basic
Agenda

1. Programing principles remind


1. Programing remind/Overview
2. Language Evaluation Criteria
3. The Compiling Process
Programing principles
Programing languages

8
Programing principles
Programing language classification

Programing languages

Level of abstraction Oriented Type Domain

Machine
Structure Compiler Web
language

Assembly Interpret
Object AI
language er

High level General


language purpose
9
Programing principles
Abstraction

10
Programing principles
Compiler vs Interpreter

Source code
?
Result
Execution
Data

Source code
Result
?
Data

11
Programing principles
Programing Domains
 Scientific Applications
 Fortran, ALGOL60
 Business Applications
 COBOL
 Artificial Intelligence
 LIPS, Prolog
 System Programing
 PL/S, BLISS, Extended ALGOL
 Web Software
 XHTML, JavaScript, PHP

12
Programing principles
Language Evaluation Criteria and Characteristics
REABILITY WRITABILITY REALIABILITY
Simplicity * * *
Data types * * *
Syntax * * *
Abstraction * *
Type checking *
Exception *
handling

 Cost of learning.
 Cost of writing.
 Cost of compiling, executing, optimization, maintaining, portability…

13
Programing principles
Compilations steps
Source code Copy all contains of header files (.h, .hpp) into target file
Preprocessi (.c, .cpp)
(.c, .h, .cpp, .hpp)
ng Macros replace (#define)
Conditional compilation (#if, #ifdef, #ifndef, #else,
(.c, .cpp) #endif)

Compilatio Do some magic 


ns Output as Assembly format (Load r1, X)
(.s)

Assembler Convert Assembly code to Machine code (0/1)

(Object file (.o, .obj)

External symbol linking


Static library (.lib, .a) Linking
Memory relocation

Executable files (.hex, .elf, .exe, .bin)


14
Programing principles
Linking: memory relocation

15
Programing principles
Compilation Phases
Lexical analyzer

Syntax analyzer

Sematic analyzer

Intermediate code
generator

Code optimizer

Code generator

16
Programing principles
Q1
#define MAX(a,b) (a>b)?a:b
inline int ReturnMaxNumber (int a, int b) {if a > b return a; else return
b;}
int ReturnMaxNumber (int a, int b) {if a > b return a; else return b;}
Which statement about Macro function and Inline function are
Incorrect?
A. Macro function is replaced in Preprocesor phase, while Inline function is replaced in Compiler
phase.

B. When running, both Macro function and Inline function will not do context saving and make
function call jumping. So they both run faster than normal function.

C. Both may take more memory code size compare to normal function.

D. Both Macro function and Inline function will harder for debugging compare to normal
17 function.
Programing principles
Inline function vs Macro
inline return_type function_name #define MACRO_NAME
(parameters) Macro_definition
{
// inline function code
}

Inline function Macro


Parsed by the compiler Expanded by the
preprocessor
It can be defined inside or It is always defined above of
outside the class the program.
Type safe: debugging is easy Debugging becomes difficult
for an inline function as error for macros as error checking
checking is done during does not occur during
compilation compilation
No function call, no jumping, replace contains, run faster,
18 more Code size
Programing principles
Q2
Below statements about Static library and Dynamic library are Correct or
Incorrect?

A. (.a, .lib) is static library file; (.so, .dll) is dynamic library file.

B. Static library is created in Compilation phase.

C. Both Static library and dynamic library can be created from multiple source files.

D. Static library is used in Assembler phase.

E. Using Static library can help to reduce SW compilation time.

F. Using Dynamic library can help to reduce SW running time.


19
Programing principles
Static library and dynamic library

20
Programing principles
Q3
int X = 0; int Y = 0;
X += X++;
Y = ++Y + Y++;
printf("Value of X: %d\n",X); printf("Value of Y: %d\n",Y);

What are output of above code?

A. X = 1; Y = 3

B. X = 2; Y = 4

C. X = 1; Y = 2

D. Wrong syntax of Y
21
Programing principles
Q4
int X[5] = {0,1,2,3,4};
int Y = 5[X];
printf("Value of Y: %d\n",Y);
What are output value of Y?

A. 5

B. 0

C. Wrong syntax. Cannot compiled

D. Unknown value
22
Agenda

1. Programing principles remind


1. Programing remind/Overview
2. Language Evaluation Criteria
3. The Compiling Process
2. Embedded system programing
1. What is embedded system?
2. Which common elements inside Embedded SW?
3. Constraints affect design choices?
4. Why C is most common language for Embedded programing?
5. What skills required for Embedded programmer?
6. RTOS & RTOS
Embedded Programing
Embedded system programing: What is embedded
system?
 Example of embedded system?

 Embedded system = Computer Hardware + Software + Additional parts

 Embedded system is combination of Computer HW and SW, and perhaps with additional
part (mechanical, electronic) designed to perform a dedicated function.

 Frequently, Embedded system is component within lager systems.

 Automotive embedded systems are connected by Communication networks.

24
Embedded Programing
Basic elements of traditional Embedded system
Communication

Sensors
Actuator

Microcontroller with SW

25
Embedded Programing
Embedded system characteristics basic

Small Size Low cost per-unit Low power consumption

26
Embedded Programing
Embedded system programing: Which common elements
inside Embedded SW?

Applications  Normally, less interact with HW.

 Device drivers developer must have detailed


Device drivers knowledge about using HW of the system

HW

27
Embedded Programing
What skills required for Embedded programmer?
 HW knowledge: must familiar with microcontroller, circuits, boards, schematic,
oscilloscope probe, VOM,…
 Peripheral interfaces knowledge: SPI, I2C, 1-Wire, UART,…

 Efficient code.

 Robust code.

 Minimal resources.

 Reusable code.

 Development tools/Debugging tools using.

 Debug skil
28
Embedded Programing
Embedded system programing: Constraints affect design
choices
Processin  Which constrains are most importance
g power
for below example product:

Life time Memory


 Digital Watch
Embedded
SW  Video game player
Number
Developme
of Unit
nt cost
product
 Mars Rover
Power
consumptio
n

29
Embedded Programing
Why C is most common language for Embedded
programing?
“Low level” of high level language.

Close with computer do, interact with HW more


easily.

Many people know and learn.

Fairly simple to learn.

Compilers available for most of processors.

Processer independence.
30
Embedded Programing
Real Time System (RTS)
 A RTS has timing constraints. The function has deadline for completion.
 The function of a Real time system specified by ability to make calculations/decisions in
timely manner.
 A RTS is not simply about the speed. It is about deadline. Guarantee that the deadlines
of the system always meet.

System must be Priority of tasks and


predictable. interrupts.

Understand worse
Handle the cases when
case performance
deadlines cannot meet.
requirements.

31
Embedded Programing
Real Time Operation System (RTOS)
 Real time task scheduling

 Resource management

 Task: a group of functions/applications. Common tasks:


 Initialization task.
 1ms task
 5ms task
 10ms task
 Background task/Algorithm task

 Scheduling: decide which task should be execute, which task should be suspensed

 Resource management: Mutex, Semaphore

32
Embedded Programing
Preemptive vs Non-Preemtive

33
Embedded Programing
Task and Timing

 What is Task Execution Time


 What is Task Deadline
 What is Task Response Time

34
Embedded Programing
Task and runnable
Tasks are managed by
TASK_10ms
OS
{
SetContext_Runnable1();
Runnable1_Run();
ReleaseContext_Runnable1(); Runnables are
managed by RTE
SetContext_Runnable2();
Runnable12_Run();
ReleaseContext_Runnable2();
…..
}

35
Agenda

1. Programing principles remind


1. Programing remind/Overview
2. Language Evaluation Criteria
3. The Compiling Process
2. Embedded system programing
1. What is embedded system?
2. Which common elements inside Embedded SW?
3. Constraints affect design choices?
4. Why C is most common language for Embedded programing?
5. What skills required for Embedded programmer?
6. RTOS
3. Some advance programing topic/related topic to embedded programming.
Embedded Programming
Bitwise Operators (1)

37
Embedded Programming
Bitwise Operators (2)
unsigned char a = 0xFF;
char b = 0xFF;

printf("%d \r\n", a>>1);


printf("%d \r\n", b>>1);
What will be output?

A. 127 ; 127
B. 127 ; -1
C. -1 ; -1
D. 127; 0

38
Embedded Programing
Pointer remind
 Determine type and value
int a[] = {1, 5, 6, 7}; of:
7. &p = ?
int* p = a; 1. a = ?
_______ 8. *p = ?
| | 2. &a = ?
9. p + 1 = ?
|___________|
3. *a = ?
| p | 0x010 10. *p + 1 = ?
|___________| 4. &a + 1 = ? 11. &p + 1 = ?
| ... |
|___________| 5. a++ = ? 12. *(p + 1) = ?
| a | 0xF00
6. p = ? 13. p++ = ?
|___________|
| |
|_ _ _ _ _ _ _ |
39
Embedded Programming
const and pointer
int* a; // Pointer to int
const int* b; // Pointer to const int
int* const c; // Const pointer to int
const int* const d; // Const pointer to const int

Which statement is showing compiler error ?

1. a++; 5. *a = 1;
2. b++; 6. *b = 1;
Why we need to use them?
3. c++; 7. *c = 1;
4. d++; 8. *d = 1;

40
Embedded Programing
Pointer to function
 Do not know the work of client side, make
program more portable.
 Make the program easier to extend.

Syntax:
<returnType>* <pointerName> ([type1 param1,
type2 param2, …])

Example:
void (*p)(int, int, int, int, int, int)
= nullptr;
p = DrawTriangle;

41
Embedded Programing
Switch..case vs multiple if..else

Switch(a)
{ If(a == 1) …
Case 1: break; Else if (a == 2) …
Case 2: break; Else if (a == 3)…
Case 3: break;
}

Jump (&a + a)

42
Code optimization hints
Hint 1: Inline function/Macro function

sint16 g_mtl_Abs_si16(Sint16 x)(if (x) > 0 return (x); else return (–x);)

INLINE Sint16 g_mtl_Abs_si16(Sint16 x)(if (x) > 0 return (x); else return (–
x);)
#define g_mtl_Abs_mac(x) (((x) >= (0)) ? (x) : (-(x)))

 Use when: function is small but called many places.


 Optimize: Run faster but more code size.

43
Code optimization hints
Hint 2: Use switch instead of multiple if-else
if(x == 1){A();} else if (x == 2) {B();} else if (x == 3) {C();} else {D();}

switch (x)
{ case 1: A(); break;
case 2: B();break;
case 3: C(); break;
default: D(); break;}

 Use when: more than 3 specific integer comparision.


 Optimize: Run faster.

44
Code optimization hints
Hint 3: Use integer type for loop index/array member
access
for(unsigned byte i = 0; i >= 100; i++){ArrayBuffer[i] = 0;}

for(int i = 0; i >= 100; i++){ArrayBuffer[i] = 0;}

 Use when: always.


 Optimize: Run faster.

45
Code optimization hints
Hint 4: Use bit shift instead of division/multiplex
unsigned integer a, b;
a = a/2; b = b*4;

unsigned integer a, b;
a = (unsign integer) (a>>1); b = (unsign integer) (b<< 2);

 Use when: always


 Optimize: Run faster.

46
Code optimization hints
Hint 5: Use integer type instead of float/double number
float a = 1.9;
if (a > 1.5f) { /* do something */}

float a = 1.9;
int b =(int)(a*10);
if (b > 15) { /* do something */}
 Use when: always
 Optimize: Run faster.

47
Code optimization hints
Hint 6: Avoid to use multiple/division operator
int a = 2; int b = 2;
a = a*2;

int a = 2;
a = a + a;

 Use when: always


 Optimize: Run faster.

48
Code optimization hints
Hint 7: Use local variable instead of global variable
extern int a; A();
void A(void){ if(a > 1) {/* Do something */}}

extern int a; A(a);


void A(int b){ if(b > 1) {/* Do something */}}

 Use when:
 Optimize: Run faster. Take more RAM.

49
Code optimization hints
Hint 8: Use if branch for higher probability
if (a == NULL_PTR){
/* Null pointer. Do nothing */
} else { A();}

if (a != NULL_PTR){
A();
}
 Use when: always for most of Microcontroller architechture.
 Optimize: Run faster. Take more RAM.

50
Code optimization hints
Hint 9: Function is called only as often as needed
Com_ReceiveSignal(1, &l_SignalData_ui8);
if (l_SignalData_ui8 == 1) { A(); }

if(NewMsgReceived_b == TRUE){
Com_ReceiveSignal(1, &l_SignalData_ui8);
if (l_SignalData_ui8 == 1) { A(); }}
 Use when: always.
 Optimize: Run faster.

51
Code optimization hints
Hint 10: Reduce number of loop
for (int i = 0; i < 1000; ++i){
if(ArrayA[i] > 0) {Flag = TRUE;}
}

for (int i = 0; i < 1000; ++i){


if(ArrayA[i] > 0) {Flag = TRUE; break;}
}

 Use when: always. Depend on Coding rule.


 Optimize: Run faster.

52
Code optimization hints
Hint 11: Use better/smarter algorithm! (1)

 Use when: always.


 Optimize: Run faster.

53
Secure programming
Overflow Compiler
optimization

Undefined behaviour
Use of uninitialized
Unspecific behaviour variable
Divide by zero

Type casting
Use object after Race condition
destroyed
Null pointer Infinite loop
54 54
Secure programming Example 2
Undefined behaviour (1) #include <limits.h>
int Example(void) {
Example 1 int b = INT_MAX-1;
int * varA = NULL; //line byte c;
1 a = (byte)b;
*varA = 0; //line if(b + 100 < b)
2 { return 1; }
return 2;
int varB; //line }
3 Example 3
int Add (int a, int
varA = &varB; //line
b)
4
{
return (a +
printf("%i\n", *varA) ; //line5
b);
printf("%i\n", varB) ; //line
6 }
Secure programming
Undefined behaviour (2)
int g = 0;
int main (void){
Int a = funcA() ;
Int b = funcB();
if(a > b)
/*………*/
}
int funcA (void){ g++;
return (g);}
int funcB (void) ){ g--;
return (g);}

56
Agenda

1. Programing principles remind


1. Programing remind/Overview
2. Language Evaluation Criteria
3. The Compiling Process
2. Embedded system programing
1. What is embedded system?
2. Which common elements inside Embedded SW?
3. Constraints affect design choices?
4. Why C is most common language for Embedded programing?
5. What skills required for Embedded programmer?
6. RTOS
3. Some advance programing topic
4. OOP principles basic
OOP principles basic
Agenda

1. Introduction
2. Class and Object
3. Inheritance
4. Function signature, overloading, overriding
5. Constructor, Destructor
6. Copy constructor
7. Operator Overloading
8. Virtual Function, Template Function

58
1. Introduction
Additional Object-Oriented features to C
REMEMBER
C++ is C with classes adding object-oriented features, such as classes,
and other enhancements to the C programming language

4 main concepts of C++:


Encapsulation
Inheritance
Polymorphism
Abstract

8
2. Class and Object

Circle, Square and Triangle: they are all shapes. We


can put them in the same class: Shape

REMEMBER

A class is just a collection of variables—


often of different types— combined with
a set of related functions

9
2. Class and Object
Circle, square, triangle are real
object. They are classfied as
“shape”
-> “Shape” is not real, it is just a Shape
definition
The variables is called member int x
data (attributes) int y

The functions is call member void Rotate()


functions (methods) void Sound()

10
2. Class and Object
Start with keyword
“class”
Syntax
class Shape
“Shape” is class name
{
int x;
int y; x,y with type int is an
member data (attribute)
void Rotate();
void Sound(); “Rotate” and “Sound”
}; are 2 member functions
(methods)
Remember the
semicolon

11
2. Class and Object
“public” keyword is
class Shape an access specifier.
There are 3 type of
{
access specifiers:
public:
public

x
Synta
int x;
int y; protected
void Rotate(); private
void Sound();
};

Access specifier affects the


attribute and methods below it
until next access specifier.
12
2. Class and Object
class Shape
{ REMEMBER
public: private access
Public - The members
int x; declared as Public are
int y; accessible from outside the
Class through an object of
void doSomeThing(){ x the class.
= 3;} Protected - The members
void Rotate(); declared as Protected are
void Sound(); accessible from outside the
public access class BUT only in a class
}; derived* from it.
Private - These members
void main() are only accessible from
{ within the class. No outside
Shape circle; Access is allowed.
circle.x = 3;
}
13
2. Class and Object 01_classandobject.cp
class myClass{ p
private: int privateMember;
public: int publicMember;

public: void setPrivateMember(int x)


{privateMember = x;};
public: int getPrivateMember(){return
privateMember;}; privateMember have
}; private access specifier:
not allow public access
void main()
{
myClass A;
A.publicMember = 5; // Perfectly legal
A.privateMember = 7; // Syntax error, this will
not compile
A.setPrivateMember(7); // Legal
14 cout << A.getPrivateMember(); // Legal
return 0; }
2. Class and Object

REMEMBER

Encapsulation is used to hide the values or state of a


structured data object inside a class, preventing unauthorized
parties' direct access to them

Keyword: public, protected and private adds encapsulation feature in C++

15
3. Inheritance
Coming back to the story, C++ provides better program
design: The same attributes,
Shape
functionality of circle,
int x square and triangle will
int y be put in Shape class.
void Rotate() When the requirement is
void Sound() updated. Just add class
Triangle and define new
member function inside it

Circle Square Triangle


void Rotate()
void Sound()
Circle and Square use the Implement new functionality
original methods Rotate and of Rotate and Sound() for
Sound Triangle
16
3. Inheritance
REMEMBE
R
Circle inherits Shape. Shape
Shape
is called base class.
int x
Circle is called derived
int y
void Rotate()
class
void Sound()
rit Inh
h e eri
In Inherit t

Circle Square Triangle


void Rotate()
void Sound()

Circle, Square, Triange inherits attributes and methods


form Shape
17
3. Inheritance
REMEMBE
R
There are 2 access

Syntax
class Shape
{ specifier: one is for data
member; one is for
public:
inheritance.
int x;
int y;
void Rotate();
void Sound(); Name of derived class
};

class Circle : public Shape Name of base class


{
}; Type/mode of
inheritance: public,
private, protected

18
3. Inheritance

BaseClass BaseClass BaseClass


public int x public int x public int x
protected int protected int protected int
y y y
private int z private int z private int z

public protected private


protected int
DerivedClass DerivedClass DerivedClass
public int x x
protected int protected int private int x
y y private int y

Practice
REMEMBER
The access scope for data members/function of derived classed is
specify by mode of inheritance.

19
3. Inheritance
REMEMBER

Inheritance allows us to define a class in terms of another class,


which makes it easier to create and maintain an application. This also
provides an opportunity to reuse the code functionality and fast
implementation time.

C++ supports multiple inheritance:

class Rectangle: public Shape, public PaintCost

21
4. Function signature, overloading, overriding
REMEMBER 02_inheritance_hiding_baseclass.cpp

1. The signature of a function consists the following information:


The name of the function
The class or namespace scope of that name
The const qualification of the function
The types of the function parameters
2. A function overloads other function when they are:
- In the same class
- Same function name
- Different in signature
3. A function overrides other function when they are:
- One in the base class and the other in derrived class
- Same in function name
- Same in signature

22
5. Constructor
class Shape Constructor have the
{ same name with class
public: name
Shape(); Shape() is a constructor
int x;
int y; Constructor should be in
public access specifier

a
y

x
t
void Rotate();
REMEMBE
void Sound();
}; RConstructor is just a
member function. Its
If we do not have difference from other
? constructor, what will member function is
happened? that it is called
What is the purpose of automatically when the
? constructor? object is created.
23
5. Constructor
REMEMBER
The sequence when an object of derived class is created:

1. Memory for “Derived” is allocated.


2. The “Derived” constructor is called
3. The compiler looks to see if we’ve asked for a particular Base class constructor.
If yes, call the base class constructor
4. The base class constructor initialization list
5. The base class constructor body executes
6. The base class constructor returns
7. The derived class constructor initialization list
8. The derived class constructor body executes
9. The derived class constructor returns

24
5. Destructor 02_inheritance_override.cpp
02_inheritance.cpp
class Shape Destructor have “~” and
{ the same name with
public: class name
~Shape(); ~Shape() is a destructor,
should be public.
int x;
int y; REMEMBE
R

a
y

x
t
Destructor is just a
void Rotate();
member function. Its
void Sound(); difference from other
}; member function is
that it is is called
If we do not have destructor,
? what will happened?
automatically when
the object is destroyed
What is the purpose of (out of scope/delete).
? destructor?
25
6. Copy constructor
class Shape Copy constructor syntax:
{ method has same name
public: of class. Parameter is
Shape(const Shape &
same type of class with
obj); constant reference
int x;
int y; REMEMBE
RCopy constructor is

a
y

x
t
called when copying
void Rotate(); an object content to
void Sound(); another object content
}; (during object
If we do not have copy initialization), like in
? constructor, what will this example:
happened? Shape myShape(2);
Shape yourShape(myShape);
What is the purpose of copy
? constructor?
Shape herShape= myShape;
func1(myShape);
26
7. Overloading operator
Does the object of CDate
? class support:

CDate today;
class CDate CDate tomorrow =
{ today++;
public:
int m_nDay;

d
h

o
e

e
a

c
t
int m_nMonth; REMEMBE
int m_nYear; R
… To use the operator on
} object , we need to
overload its operator.

27
7. Overloading operator
class CDate Prefix increment operator
{
public:
int m_nDay;
int m_nMonth;
int m_nYear;
CDate operator ++ void main()
() {
CDate operator ++ CDate today;
(int) today++;
} CDate tomorrow =
++today;
Postfix increment }
operator

28
7. Overloading operator 04_Operator1.cpp

class CDate Prefix increment operator


{
public:
int m_nDay;
int m_nMonth;
int m_nYear;
CDate operator ++ void main()
() {
CDate operator ++ CDate today;
(int) today++;
} CDate tomorrow =
++today;
Postfix increment }
operator

29
7. Overloading operator
REMEMBE REMEMBE
ROperator can be Name ROperator cannot Name
overloaded be overloaded
++ Increment . Member selection
-- Decrement .* Pointer-to-member
selection
* Pointer dereference
:: Scope resolution
-> Member selection
?: Conditional ternary
! Logical NOT operator
& Address-of sizeof Gets the size of an
object/class type
~ One’s complement
+ or - Unary
plus/negation
Conversion, binary, Conversion, binary,
comparison, comparison,
subscript, function subscript, function
operators operators

30
8. Virtual function, polymorphism
Human

GoShopping(){
print(“Go shopping”) };

Girl Boy
public: GoShopping(){ public: GoShopping()
print(“I love it”) { print(“I hate
}; it”) };

main(){ //What in the output


Human h; ? h.GoShopping();
Girl alice; alice.GoShopping();
Boy tom; tom.GoShopping();
}
32
8. Virtual function, polymorphism
Human

virtual GoShopping(){
print(“Go shopping”) };

Girl Boy
public: GoShopping(){ public: GoShopping()
print(“I love it”) { print(“I hate
}; It”) };
REMEMBE Virtual keyword
R adds polymorphism
With polymorphism, you do not
need to know the alice and tom
are Boy or Girl. You just need to
know that they are Human.

33
8. Virtual function, polymorphism
Human

virtual GoShopping() = 0;

Girl Boy
public: GoShopping(){ public: GoShopping()
print(“I love it”) { print(“I hate
}; It”) };
REMEMBE Method without
R method . It implementation with
GoShopping is a virtual “=0”
becomes pure virtual method.
GoShopping method does not need
implementation. Human now
becomes an abstract class.
34
8. Virtual function, polymorphism 03_polymorphism_boy_girl.cpp

Human

virtual GoShopping(){
print(“Go shopping”) };
Girl alice;
Girl Boy Boy tom;
public: GoShopping(){
public: GoShopping(){
print(“I hate
Human& h1 = alice;
print(“I love it”) }; It”) }; Human& h2 = tom;
h1.GoShopping();
REMEMBE //I love it
R
Method 1 to apply h2.GoShopping();
polymorphism: //I hate it
A reference (base class type)
refers to an object of derived
class

35
8. Virtual function, polymorphism 03_01_Virtual.cpp

Human

virtual GoShopping(){
print(“Go shopping”) };
Girl alice;
Boy tom;
Girl Boy

public: GoShopping(){
Human* h1 =
public: GoShopping(){ print(“I hate &alice;
print(“I love it”) }; It”) };
Human* h2 = &tom;
REMEMBE h1->GoShopping();
R //I love it
Method 2 to apply h2->GoShopping();
polymorphism: //I hate it
A pointer of base class type
points to an address of an
derived class object.

36
8. Template Function

template <typename objectType>


objectType & GetMax (const objectType & value1, const objectType &
value2)
{

x
Synta
if (value1 > value2)
return value1;
else
return value2;
};

int nInteger1 = 25;


int nInteger2 = 40;
int nMaxValue = GetMax <int> (nInteger1, nInteger2);
double dDouble1 = 1.1;
double dDouble2 = 1.001;
double dMaxValue = GetMax <double> (nDouble1, nDouble2);

37
8. Template Class
template <typename T>
class CMyFirstTemplateClass
{
public:

x
Synta
void SetVariable (T& newValue) { m_Value = newValue; };
T& GetValue () {return m_Value;};
private:
T m_Value;
};

CMyFirstTemplate <int> mHoldInteger; // Template instantiation


mHoldInteger.SetValue (5);
std::cout << “The value stored is: “ << mHoldInteger.GetValue ();

CMyFirstTemplate <char*> mHoldString;


mHoldInteger.SetValue (“Sample string”);
std::cout << “The value stored is: “ << mHoldInteger.GetValue ();

38
Recommended learning resources / references
 The C++ Tutorial | Learn C++ (learncpp.com)
 C++ Programming Language - GeeksforGeeks
 C++ Programming Tutorials Playlist - YouTube
 Example references:
 Amazon.com: C++ in One Hour a Day, Sams Teach Yourself: 9780789757746: Rao, Siddhartha: B
ooks
Thank you!

89

You might also like