BGSV Embedded Academy(BEA)
Technical
Competence
T1: Automotive Basics
(Sensor, SW, Mobility
Solution)
T2: Automotive SW
Architecture (AUTOSAR)
T3: Embedded
Programming
T5: Test Overview
Methodological
Competence
M1: SW Development
Lifecycle
M3: Clean Code
Process
Competence
P1: Requirements
Engineering
P2: Design Principles
P3: Review
P4: Safety & Security
BGSV EMBEDDED ACADEMY
Purpose: Develop basic general embedded competence
Focused Program to Develop Embedded Competence
Classroom training, Online Self-learning, Live Demo
3.
Disclaimer
This slideis 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.
Objectives &
Assumptions
5
Remind generalprogramming 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++
6.
Agenda
1. Programing principlesremind
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
7.
Agenda
1. Programing principlesremind
1. Programing remind/Overview
2. Language Evaluation Criteria
3. The Compiling Process
Programing language classification
Programingprinciples
9
Programing languages
Level of abstraction
Machine
language
Assembly
language
High level
language
Oriented
Structure
Object
Type
Compiler
Interpret
er
Domain
Web
AI
General
purpose
Q1
Programing principles
17
#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 function.
E. An Class member can be access inside both Inline function and Macro function.
18.
Inline function vsMacro
Programing principles
18
#define MACRO_NAME
Macro_definition
inline return_type function_name
(parameters)
{
// inline function code
}
Inline function Macro
Parsed by the compiler Expanded by the preprocessor
It can be defined inside or
outside the class
It is always defined above of the
program.
Type safe: debugging is easy
for an inline function as error
checking is done during
compilation
Debugging becomes difficult for
macros as error checking does
not occur during compilation
No function call, no jumping, replace contains, run faster, more
Code size
19.
Q2
Programing principles
19
Below statementsabout 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.
Q3
Programing principles
21
int X= 0; int Y = 0;
X += X++;
Y = ++Y + Y++;
printf("Value of X: %dn",X); printf("Value of Y: %dn",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
22.
Q4
Programing principles
22
int X[5]= {0,1,2,3,4};
int Y = 5[X];
printf("Value of Y: %dn",Y);
What are output value of Y?
A. 5
B. 0
C. Wrong syntax. Cannot compiled
D. Unknown value
23.
Agenda
1. Programing principlesremind
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
24.
Embedded system programing:What is embedded system?
Embedded Programing
24
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.
25.
Basic elements oftraditional Embedded system
Embedded Programing
25
Microcontroller with SW
Sensors
Actuator
Communication
Embedded system programing:Which common elements
inside Embedded SW?
Embedded Programing
27
HW
Device drivers
Applications Normally, less interact with HW.
Device drivers developer must have detailed knowledge
about using HW of the system
Embedded system programing:Constraints affect design
choices
Embedded Programing
29
Embedded
SW
Processing
power
Memory
Number
of Unit
product
Power
consumptio
n
Developmen
t cost
Life time
Which constrains are most importance for
below example product:
Digital Watch
Video game player
Mars Rover
30.
Why C ismost common language for Embedded programing?
Embedded Programing
30
“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.
31.
Real Time System(RTS)
Embedded Programing
31
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
predictable.
Priority of tasks and
interrupts.
Understand worse
case performance
requirements.
Handle the cases when
deadlines cannot meet.
32.
Real Time OperationSystem (RTOS)
Embedded Programing
32
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
Task and Timing
EmbeddedPrograming
34
What is Task Execution Time
What is Task Deadline
What is Task Response Time
35.
Task and runnable
EmbeddedPrograming
35
TASK_10ms
{
SetContext_Runnable1();
Runnable1_Run();
ReleaseContext_Runnable1();
SetContext_Runnable2();
Runnable12_Run();
ReleaseContext_Runnable2();
…..
}
Tasks are managed by OS
Runnables are
managed by RTE
36.
Agenda
1. Programing principlesremind
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.
Bitwise Operators (2)
EmbeddedProgramming
38
unsigned char a = 0xFF;
char b = 0xFF;
printf("%d rn", a>>1);
printf("%d rn", b>>1);
What will be output?
A. 127 ; 127
B. 127 ; -1
C. -1 ; -1
D. 127; 0
const and pointer
EmbeddedProgramming
40
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++;
2. b++;
3. c++;
4. d++;
5. *a = 1;
6. *b = 1;
7. *c = 1;
8. *d = 1;
Why we need to use them?
41.
Pointer to function
EmbeddedPrograming
41
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;
42.
Switch..case vs multipleif..else
Embedded Programing
42
Switch(a)
{
Case 1: break;
Case 2: break;
Case 3: break;
}
If(a == 1) …
Else if (a == 2) …
Else if (a == 3)…
Jump (&a + a)
43.
43
Hint 1: Inlinefunction/Macro function
Code optimization hints
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.
sint16 g_mtl_Abs_si16(Sint16 x)(if (x) > 0 return (x); else return (–x);)
44.
44
Hint 2: Useswitch instead of multiple if-else
Code optimization hints
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.
if(x == 1){A();} else if (x == 2) {B();} else if (x == 3) {C();} else {D();}
45.
45
Hint 3: Useinteger type for loop index/array member access
Code optimization hints
for(int i = 0; i >= 100; i++){ArrayBuffer[i] = 0;}
Use when: always.
Optimize: Run faster.
for(unsigned byte i = 0; i >= 100; i++){ArrayBuffer[i] = 0;}
46.
46
Hint 4: Usebit shift instead of division/multiplex
Code optimization hints
unsigned integer a, b;
a = (unsign integer) (a>>1); b = (unsign integer) (b<< 2);
Use when: always
Optimize: Run faster.
unsigned integer a, b;
a = a/2; b = b*4;
47.
47
Hint 5: Useinteger type instead of float/double number
Code optimization hints
float a = 1.9;
int b =(int)(a*10);
if (b > 15) { /* do something */}
Use when: always
Optimize: Run faster.
float a = 1.9;
if (a > 1.5f) { /* do something */}
48.
48
Hint 6: Avoidto use multiple/division operator
Code optimization hints
int a = 2;
a = a + a;
Use when: always
Optimize: Run faster.
int a = 2; int b = 2;
a = a*2;
49.
49
Hint 7: Uselocal variable instead of global variable
Code optimization hints
extern int a; A(a);
void A(int b){ if(b > 1) {/* Do something */}}
Use when:
Optimize: Run faster. Take more RAM.
extern int a; A();
void A(void){ if(a > 1) {/* Do something */}}
50.
50
Hint 8: Useif branch for higher probability
Code optimization hints
if (a != NULL_PTR){
A();
}
Use when: always for most of Microcontroller architechture.
Optimize: Run faster. Take more RAM.
if (a == NULL_PTR){
/* Null pointer. Do nothing */
} else { A();}
51.
51
Hint 9: Functionis called only as often as needed
Code optimization hints
if(NewMsgReceived_b == TRUE){
Com_ReceiveSignal(1, &l_SignalData_ui8);
if (l_SignalData_ui8 == 1) { A(); }}
Use when: always.
Optimize: Run faster.
Com_ReceiveSignal(1, &l_SignalData_ui8);
if (l_SignalData_ui8 == 1) { A(); }
52.
52
Hint 10: Reducenumber of loop
Code optimization hints
for (int i = 0; i < 1000; ++i){
if(ArrayA[i] > 0) {Flag = TRUE; break;}
}
Use when: always. Depend on Coding rule.
Optimize: Run faster.
for (int i = 0; i < 1000; ++i){
if(ArrayA[i] > 0) {Flag = TRUE;}
}
53.
53
Hint 11: Usebetter/smarter algorithm! (1)
Code optimization hints
Use when: always.
Optimize: Run faster.
54.
54
Secure programming
54
Undefined behaviour
OverflowCompiler optimization
Unspecific behaviour
Use of uninitialized
variable
Divide by zero
Type casting
Use object after destroyed Race condition
Null pointer Infinite loop
55.
Secure programming
Undefined behaviour(1)
int * varA = NULL; //line
1
*varA = 0; //line
2
int varB; //line
3
varA = &varB; //line
4
printf("%in", *varA) ; //line5
printf("%in", varB) ; //line
6
int Add (int a, int
b)
{
return (a +
b);
}
#include <limits.h>
int Example(void) {
int b = INT_MAX-1;
byte c;
a = (byte)b;
if(b + 100 < b)
{ return 1; }
return 2;
}
Example 1
Example 3
Example 2
56.
Secure programming
Undefined behaviour(2)
56
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);}
57.
Agenda
1. Programing principlesremind
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
58.
OOP principles basic
Agenda
58
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
59.
8
1. Introduction
Additional Object-Orientedfeatures to C
C++ is C with classes adding object-oriented features, such as classes, and other
enhancements to the C programming language
REMEMBER
4 main concepts of C++:
Encapsulation
Inheritance
Polymorphism
Abstract
60.
9
2. Class andObject
Circle, Square and Triangle: they are all shapes. We can
put them in the same class: Shape
A class is just a collection of variables—
often of different types— combined with a
set of related functions
REMEMBER
61.
10
2. Class andObject
int x
int y
void Rotate()
void Sound()
Shape
The variables is called member data
(attributes)
The functions is call member functions
(methods)
Circle, square, triangle are real
object. They are classfied as “shape”
-> “Shape” is not real, it is just a
definition
62.
11
2. Class andObject
class Shape
{
int x;
int y;
void Rotate();
void Sound();
};
Syntax
Remember the semicolon
Start with keyword “class”
x,y with type int is an
member data (attribute)
“Rotate” and “Sound” are 2
member functions
(methods)
“Shape” is class name
63.
12
2. Class andObject
class Shape
{
public:
int x;
int y;
void Rotate();
void Sound();
};
Syntax
“public” keyword is
an access specifier.
There are 3 type of
access specifiers:
public
protected
private
Access specifier affects the
attribute and methods below it
until next access specifier.
64.
13
2. Class andObject
class Shape
{
public:
int x;
int y;
void doSomeThing(){ x = 3;}
void Rotate();
void Sound();
};
void main()
{
Shape circle;
circle.x = 3;
}
public access
Public - The members declared
as Public are accessible from
outside the Class through an
object of the class.
Protected - The members
declared as Protected are
accessible from outside the
class BUT only in a class
derived* from it.
Private - These members are
only accessible from within the
class. No outside Access is
allowed.
REMEMBER
private access
65.
14
2. Class andObject
class myClass{
private: int privateMember;
public: int publicMember;
public: void setPrivateMember(int x){privateMember =
x;};
public: int getPrivateMember(){return
privateMember;};
};
void main()
{
myClass A;
A.publicMember = 5; // Perfectly legal
A.privateMember = 7; // Syntax error, this will not
compile
A.setPrivateMember(7); // Legal
cout << A.getPrivateMember(); // Legal
return 0; }
privateMember have
private access specifier:
not allow public access
01_classandobject.cpp
66.
15
2. Class andObject
Encapsulation is used to hide the values or state of a structured
data object inside a class, preventing unauthorized parties' direct
access to them
REMEMBER
Keyword: public, protected and private adds encapsulation feature in C++
67.
16
3. Inheritance
Coming backto the story, C++ provides better program design:
int x
int y
void Rotate()
void Sound()
Shape
Circle Square
void Rotate()
void Sound()
Triangle
The same attributes,
functionality of circle,
square and triangle will be
put in Shape class.
When the requirement is
updated. Just add class
Triangle and define new
member function inside it
Implement new functionality of
Rotate and Sound() for Triangle
Circle and Square use the
original methods Rotate and
Sound
68.
17
3. Inheritance
int x
inty
void Rotate()
void Sound()
Shape
Circle Square
void Rotate()
void Sound()
Triangle
Circle, Square, Triange inherits attributes and methods form
Shape
Inherit
Inherit
Inherit
Circle inherits Shape. Shape is
called base class. Circle is
called derived class
REMEMBER
69.
18
3. Inheritance
class Shape
{
public:
intx;
int y;
void Rotate();
void Sound();
};
class Circle : public Shape
{
};
Syntax
Type/mode of
inheritance: public,
private, protected
Name of base class
Name of derived class
There are 2 access
specifier: one is for data
member; one is for
inheritance.
REMEMBER
70.
19
3. Inheritance
public intx
protected int
y
private int z
BaseClass
DerivedClass
public
public int x
protected int
y
public int x
protected int
y
private int z
BaseClass
DerivedClass
protected
protected int
x
protected int
y
public int x
protected int
y
private int z
BaseClass
DerivedClass
private
private int x
private int y
The access scope for data members/function of derived classed is
specify by mode of inheritance.
REMEMBER Practice
71.
21
3. Inheritance
Inheritance allowsus 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.
REMEMBER
C++ supports multiple inheritance:
class Rectangle: public Shape, public PaintCost
72.
22
4. Function signature,overloading, overriding
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
REMEMBER 02_inheritance_hiding_baseclass.cpp
73.
23
5. Constructor
class Shape
{
public:
Shape();
intx;
int y;
void Rotate();
void Sound();
};
S
y
n
t
a
x
Shape() is a constructor
Constructor have the same
name with class name
Constructor should be in
public access specifier
Constructor is just a
member function. Its
difference from other
member function is that
it is called automatically
when the object is
created.
REMEMBER
?
If we do not have constructor,
what will happened?
?
What is the purpose of
constructor?
74.
24
5. Constructor
The sequencewhen 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
REMEMBER
75.
25
5. Destructor
class Shape
{
public:
~Shape();
intx;
int y;
void Rotate();
void Sound();
};
S
y
n
t
a
x
~Shape() is a destructor,
should be public.
Destructor have “~” and
the same name with class
name
Destructor is just a
member function. Its
difference from other
member function is that
it is is called
automatically when the
object is destroyed (out
of scope/delete).
REMEMBER
?
If we do not have destructor,
what will happened?
?
What is the purpose of
destructor?
02_inheritance_override.cpp
02_inheritance.cpp
76.
26
6. Copy constructor
classShape
{
public:
Shape(const Shape & obj);
int x;
int y;
void Rotate();
void Sound();
};
S
y
n
t
a
x
Copy constructor syntax:
method has same name of
class. Parameter is same
type of class with constant
reference
Copy constructor is
called when copying an
object content to
another object content
(during object
initialization), like in this
example:
Shape myShape(2);
Shape yourShape(myShape);
Shape herShape= myShape;
func1(myShape);
REMEMBER
?
If we do not have copy
constructor, what will
happened?
?
What is the purpose of copy
constructor?
77.
27
7. Overloading operator
classCDate
{
public:
int m_nDay;
int m_nMonth;
int m_nYear;
…
}
R
e
a
d
th
e
co
d
e
? Does the object of CDate
class support:
CDate today;
CDate tomorrow = today++;
To use the operator on
object , we need to
overload its operator.
REMEMBER
30
7. Overloading operator
Operatorcannot be
overloaded
Name
. Member selection
.* Pointer-to-member
selection
:: Scope resolution
? : Conditional ternary
operator
sizeof Gets the size of an
object/class type
REMEMBER
Operator can be
overloaded
Name
++ Increment
-- Decrement
* Pointer dereference
-> Member selection
! Logical NOT
& Address-of
~ One’s complement
+ or - Unary plus/negation
Conversion, binary,
comparison,
subscript, function
operators
Conversion, binary,
comparison,
subscript, function
operators
REMEMBER
81.
32
8. Virtual function,polymorphism
GoShopping(){
print(“Go shopping”) };
Human
public: GoShopping(){
print(“I hate
it”) };
Boy
public: GoShopping(){
print(“I love it”) };
Girl
main(){
Human h;
Girl alice;
Boy tom;
}
?
//What in the output
h.GoShopping();
alice.GoShopping();
tom.GoShopping();
82.
33
8. Virtual function,polymorphism
virtual GoShopping(){
print(“Go shopping”) };
Human
public: GoShopping(){
print(“I hate
It”) };
Boy
public: GoShopping(){
print(“I love it”) };
Girl
Virtual keyword
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.
REMEMBER
83.
34
8. Virtual function,polymorphism
virtual GoShopping() = 0;
Human
public: GoShopping(){
print(“I hate
It”) };
Boy
public: GoShopping(){
print(“I love it”) };
Girl
Method without
implementation with
“=0”
GoShopping is a virtual method . It
becomes pure virtual method.
GoShopping method does not need
implementation. Human now becomes
an abstract class.
REMEMBER
84.
35
8. Virtual function,polymorphism
virtual GoShopping(){
print(“Go shopping”) };
Human
public: GoShopping(){
print(“I hate
It”) };
Boy
public: GoShopping(){
print(“I love it”) };
Girl
Method 1 to apply
polymorphism:
A reference (base class type) refers
to an object of derived class
REMEMBER
Girl alice;
Boy tom;
Human& h1 = alice;
Human& h2 = tom;
h1.GoShopping();
//I love it
h2.GoShopping();
//I hate it
03_polymorphism_boy_girl.cpp
85.
36
8. Virtual function,polymorphism
virtual GoShopping(){
print(“Go shopping”) };
Human
public: GoShopping(){
print(“I hate
It”) };
Boy
public: GoShopping(){
print(“I love it”) };
Girl
Method 2 to apply
polymorphism:
A pointer of base class type points
to an address of an derived class
object.
REMEMBER
Girl alice;
Boy tom;
Human* h1 = &alice;
Human* h2 = &tom;
h1->GoShopping();
//I love it
h2->GoShopping();
//I hate it
03_01_Virtual.cpp
38
8. Template Class
template<typename T>
class CMyFirstTemplateClass
{
public:
void SetVariable (T& newValue) { m_Value = newValue; };
T& GetValue () {return m_Value;};
private:
T m_Value;
};
Syntax
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 ();
88.
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: Books
#17 E is wrong answer. Macro does not support datatype and must be written in above of program.
#19 A – Correct
B – Incorrect.
C – Correct
D – Incorrect. Static library is used in Linker phase, Dynamic library is used in during runtime.
E – Correct. For unchanged codes, using library help to reduce SW compilation phase, because they was compiled already
F – Incorrect. Using dynamic may increase SW runtime, because the program has to seek and switching to dynamic library. But benefit is it only be used when needed.
#58 This training is intended for developers or students who want to revisit the concept of Object Oriented Programming (OOP) or have no idea about OOP.
Prerequisite background:
C programming.
Data structures and algorithms.
Learning objectives:
Understand concepts of OOP
Understand the use of OOP principles through examples
Apply common principles of OOP
Be able to extend the knowledge of OOP by recommended reading resources.
#59 Develop the OOP idea based on the C concept.
Emphasis that C++ is based on the C concept with additional features.
#60 Distinguish between the class and object:
Class: A class in C++ is the building block that leads to Object-Oriented programming. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object.
#61 An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.
Source: C++ Classes and Objects - GeeksforGeeks
#62 The syntax of defining a class.
Can link to the syntax of struct in C.
In C++, a structure is the same as a class except for a few differences. The most important of them is security. A Structure is not secure and cannot hide its implementation details from the end-user while a class is secure and can hide its programming and designing details. Following are some differences between a class and a structure.
Class: Members of a class are private by default. It is a reference type data type. It is declared using the class keyword.
Structure Members of a structure are public by default. It is a value type data type. It is declared using the struct keyword.
Structure vs class in C++ - GeeksforGeeks
#63 Emphasize the priority when multiple access specifiers are given within a class.:
1) The members declared after the access specifier have public member access
2) The members declared after the access specifier have protected member access
3) The members declared after the access specifier have private member access
Access specifiers - cppreference.com
#64 1. Public: All the class members declared under the public specifier will be available to everyone. The data members and member functions declared as public can be accessed by other classes and functions too. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class.
2. Private: The class members declared as private can be accessed only by the member functions inside the class. They are not allowed to be accessed directly by any object or function outside the class.
3. Protected: Protected access modifier is similar to private access modifier in the sense that it can’t be accessed outside of it’s class unless with the help of friend class, the difference is that the class members declared as Protected can be accessed by any subclass(derived class) of that class as well.
Source: Access Modifiers in C++ - GeeksforGeeks
#65 Demonstrates the use of access specifiers.
Show the compiling errors when violating the access scope.
#66 In normal terms Encapsulation is defined as wrapping up of data and information under a single unit. In Object Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulates them.
Consider a real-life example of encapsulation, in a company there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keep records of all the data related to finance. Similarly the sales section handles all the sales related activities and keep records of all the sales. Now there may arise a situation when for some reason an official from finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of sales section and the employees that can manipulate them are wrapped under a single name “sales section”.
Encapsulation also lead to data abstraction or hiding. As using encapsulation also hides the data. In the above example the data of any of the section like sales, finance or accounts is hidden from any other section.
Encapsulation in C++ - GeeksforGeeks
#67 Using inheritance, we have to write the functions only one time instead of many times as we have inherited the rest of the three classes from the base class.
Beside that, the functions can be “rewritten” in the child class.
#68 Derived Class: The class that inherits properties from another class is called Subclass or Derived Class.
Class Class: The class whose properties are inherited by a subclass is called Base Class or Superclass.
#69 Modes of Inheritance: There are 3 modes of inheritance.
Public Mode: If we derive a subclass from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in the derived class.
Protected Mode: If we derive a subclass from a Protected base class. Then both public members and protected members of the base class will become protected in the derived class.
Private Mode: If we derive a subclass from a Private base class. Then both public members and protected members of the base class will become Private in the derived class.
Inheritance in C++ - GeeksforGeeks
#70 Note: The private members in the base class cannot be directly accessed in the derived class, while protected members can be directly accessed.
#72 Function Signature
A function's signature includes the function's name and the number, order and type of its formal parameters.
Two overloaded functions must not have the same signature.
The return value is not part of a function's signature.
These two functions have the same signature: int Divide (int n, int m) ; double Divide (int n, int m) ;
Resolving Overloaded Functions
When a function call involves an overloaded name, the compiler must determine which function to call.
Rule 1, Exact Match: Call the function with a parameter list that matches the argument list exactly in number, order and type.
Rule 2, Match using type conversion: Call a function if there exist type converters which can convert some of the arguments in the function call to match the formal parameters in a function definition.
Rule 1 has precedence.
Errors in Resolving Overloaded Functions
If no matches are found using Rule 1 (exact match) or Rule 2 (match using type conversion), the compiler generates an error.
If two functions have the same signature, two functions will match using Rule 1. The compiler complains when it encounters the second function definition.
If two or more matches are found using Rule 2, the compiler complains the function call is ambiguous. The compiler complains when it encounters the ambiguous function call.
Overloading Functions (umbc.edu)
#73 A constructor is different from normal functions in following ways:
Constructor has same name as the class itself
Default Constructors don’t have input argument, however, Copy and Parameterized Constructors have input arguments
Constructors don’t have return type
A constructor is automatically called when an object is created.
It must be placed in public section of class.
If we do not specify a constructor, C++ compiler generates a default constructor for object (expects no parameters and has an empty body).
#75 Properties of Destructor:
Destructor function is automatically invoked when the objects are destroyed.
It cannot be declared static or const.
The destructor does not have arguments.
It has no return type not even void.
An object of a class with a Destructor cannot become a member of the union.
A destructor should be declared in the public section of the class.
The programmer cannot access the address of destructor.
When is destructor called?
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called
How are destructors different from a normal member function?
Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything
Destructors in C++ - GeeksforGeeks
#76 When is copy constructor called?
In C++, a Copy Constructor may be called in the following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an argument.
3. When an object is constructed based on another object of the same class.
4. When the compiler generates a temporary object.
It is, however, not guaranteed that a copy constructor will be called in all these cases, because the C++ Standard allows the compiler to optimize the copy away in certain cases, one example
#77 In C++, we can make operators to work for user defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator ‘+’ in a class like String so that we can concatenate two strings by just using +. Other example classes where arithmetic operators may be overloaded are Complex Number, Fractional Number, Big Integer, etc.
Operator Overloading in C++ - GeeksforGeeks
#79 Emphasize the function signature of prefix and postfix operator.
#80 Why can’t . (dot), ::, ?: and sizeof be overloaded?
See this for answers from Stroustrup himself.
Important points about operator overloading
1) For operator overloading to work, at least one of the operands must be a user defined class object.
2) Assignment Operator: Compiler automatically creates a default assignment operator with every class. The default assignment operator does assign all members of right side to the left side and works fine most of the cases (this behavior is same as copy constructor). See this for more details.
3) Conversion Operator: We can also write conversion operators that can be used to convert one type to another type.
Operator Overloading in C++ - GeeksforGeeks
#81 The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism, a person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism. Polymorphism is considered as one of the important features of Object Oriented Programming.
#82 A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined (Overriden) in the derived class. It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime. This technique of falls under Runtime Polymorphism.
The term Polymorphism means the ability to take many forms. It occurs if there is a hierarchy of classes that are all related to each other by inheritance. In simple words, when we break down Polymorphism into ‘Poly – Many’ and ‘morphism – Forms’ it means showing different characteristics in different situations.
Virtual Functions and Runtime Polymorphism in C++ - GeeksforGeeks
#83 Sometimes implementation of all function cannot be provided in a base class because we don’t know the implementation. Such a class is called abstract class. For example, let Shape be a base class. We cannot provide implementation of function draw() in Shape, but we know every derived class must have implementation of draw(). Similarly an Animal class doesn’t have implementation of move() (assuming that all animals move), but all animals must know how to move. We cannot create objects of abstract classes.
A pure virtual function (or abstract function) in C++ is a virtual function for which we can have implementation, But we must override that function in the derived class, otherwise the derived class will also become abstract class (For more info about where we provide implementation for such functions refer to this https://stackoverflow.com/questions/2089083/pure-virtual-function-with-implementation). A pure virtual function is declared by assigning 0 in declaration. See the following example.
Pure Virtual Functions and Abstract Classes in C++ - GeeksforGeeks
#84 Demonstrate some polymorphism implementation.
Emphasize on the effect of the virtual keyword.
#86 A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by keyword ‘class’.
Function Templates We write a generic function that can be used for different data types. Examples of function templates are sort(), max(), min(), printArray().
Know more on Generics in C++
Templates in C++ with Examples - GeeksforGeeks
#87 Class Templates Like function templates, class templates are useful when a class defines something that is independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc.
#89 Useful video in Vietnamese:
https://www.youtube.com/watch?v=_s7J8duwKSo