Lecture 7
Lecture 7
Lecture 7
0
https://www.geeksforgeeks.org/inheritance-in-c/
1
C vs C++ Inheritance Example
C Code
1 // "Base" class , Vehicle
2 typedef struct vehicle {
3 int seats_ ; // number of seats on the vehicle
4 int capacity_ ; // amount of fuel of the gas tank
5 char* brand_ ; // make of the vehicle
6 } vehicle_t ;
C++ Code
1 class Vehicle {
2 private :
3 int seats_ = 0; // number of seats on the vehicle
4 int capacity_ = 0; // amount of fuel of the gas tank
5 string brand_ ; // make of the vehicle
2
Inheritance
0
https://google.github.io/styleguide/cppguide.html#Inheritance
3
Public inheritance
Public inheritance stands for “is a”
relationship, i.e. if class Derived inherits
publicly from class Base we say, that
Derived is a kind of Base
1 class Derived : public Base {
2 // Contents of the derived class .
3 };
5
Function overriding
6
Overloading vs overriding
8
How virtual works
9
Using interfaces
10
1 # include <iostream >
2 using std :: cout;
3 using std :: endl;
4 struct Printable { // Saving space . Should be a class .
5 virtual void Print () const = 0;
6 };
7 struct A : public Printable {
8 void Print () const override { cout << "A" << endl; }
9 };
10 struct B : public Printable {
11 void Print () const override { cout << "B" << endl; }
12 };
13 void Print( const Printable & var) { var.Print (); }
14 int main () {
15 Print (A());
16 Print (B());
17 return 0;
18 }
11
Geometry2D and Image
Open3D::Geometry::Geometry2D
1 class Geometry2D {
2 public :
3 Geometry & Clear () = 0;
4 bool IsEmpty () const = 0;
5 virtual Eigen :: Vector2d GetMinBound () const = 0;
6 virtual Eigen :: Vector2d GetMaxBound () const = 0;
7 };
Open3D::Geometry::Image
1 class Image : public Geometry2D {
2 public :
3 Geometry & Clear () override ;
4 bool IsEmpty () const override ;
5 virtual Eigen :: Vector2d GetMinBound () const override ;
6 virtual Eigen :: Vector2d GetMaxBound () const override ;
7 };
12
Polymorphism
13
Polymorphism Example 1
1 class Rectangle {
2 public :
3 Rectangle (int w, int h) : width_ {w}, height_ {h} {}
4 int width () const { return width_ ; }
5 int height () const { return height_ ; }
6
7 protected :
8 int width_ = 0;
9 int height_ = 0;
10 };
11
12 class Square : public Rectangle {
13 public :
14 explicit Square (int size) : Rectangle {size , size} {}
15 };
14
Polymorphism Example 1
15
Polymorphism Example 2
1 class Rectangle {
2 public :
3 Rectangle (int w, int h) : width_ {w}, height_ {h} {}
4 int width () const { return width_ ; }
5 int height () const { return height_ ; }
6
7 void Print () const {
8 cout << "Rec:" << width_ << " " << height_ << endl;
9 }
1 class Square : public Rectangle {
2 public :
3 explicit Square (int size) : Rectangle {size , size} {}
4 void Print () const {
5 cout << "Sq:" << width_ << " " << height_ << endl;
6 }
7 };
16
Polymorphism Example 2
17
1 virtual void Rectangle :: Print () const {
2 cout << "Rec:" << width_ << " " << height_ << endl;
3 }
1 int main () {
2 Square sq (10);
3 Rectangle rec (10, 15);
4
5 PrintShape (rec);
6 PrintShape (sq);
7
8 return 0;
9 }
18
Now we are using Runtime Polymorphism,
we are printing shapes to the std::cout and
deciding at runtime with type of shape it is
19
std::vector<Rectangle>
1 # include <memory >
2 # include <vector >
3 using std :: make_unique ;
4 using std :: unique_ptr ;
5 using std :: vector ;
6
7 int main () {
8 vector <unique_ptr <Rectangle >> shapes ;
9 shapes . emplace_back ( make_unique <Rectangle >(10 , 15));
10 shapes . emplace_back ( make_unique <Square >(10));
11
12 for ( const auto &shape : shapes ) {
13 shape ->Print ();
14 }
15
16 return 0;
17 }
20
When is it useful?
21
Creating a class hierarchy
Sometimes classes must form a hierarchy
Distinguish between is a and has a to test
if the classes should be in one hierarchy:
Square is a Shape: can inherit from Shape
Student is a Human: can inherit from Human
Car has a Wheel: should not inherit each other
GOOGLE-STYLE Prefer composition,
i.e. including an object of another class as a
member of your class
NACHO-STYLE Don’t get too excited, use it
only when improves
code performance/readability.
0
https://google.github.io/styleguide/cppguide.html#Inheritance
22
Casting type of variables
23
Casting type of variables
24
static_cast
Syntax: static_cast<NewType>(variable)
Convert type of a variable at compile time
Rarely needed to be used explicitly
Can happen implicitly for some types,
e.g. float can be cast to int
Pointer to an object of a Derived class can
be upcast to a pointer of a Base class
Enum value can be caster to int or float
Full specification is complex!
0
Full specs: http://en.cppreference.com/w/cpp/language/static_cast
25
dynamic_cast
Syntax: dynamic_cast<Base*>(derived_ptr)
Used to convert a pointer to a variable of
Derived type to a pointer of a Base type
Conversion happens at runtime
If derived_ptr cannot be converted to Base*
returns a nullptr
GOOGLE-STYLE Avoid using dynamic casting
0
Full specs: http://en.cppreference.com/w/cpp/language/dynamic_cast
26
reinterpret_cast
Syntax:
reinterpret_cast<NewType>(variable)
Reinterpret the bytes of a variable as
another type
We must know what we are doing!
Mostly used when writing binary data
0
Full specs: http://en.cppreference.com/w/cpp/language/reinterpret_cast
27
const_cast
Syntax: const_cast<NewType>(variable)
Used to “constify” objects
Used to “de-constify” objects
Not widely used
0
Full specs: http://en.cppreference.com/w/cpp/language/const_cast
28
Google Style
29
Google Style
30
Google Style
31
Using strategy pattern
32
1 class Strategy {
2 public :
3 virtual void Print () const = 0;
4 };
35
Do not overuse it
36
Singleton Pattern
We want only one instance of a given class.
Without C++ this would be a if/else mess.
C++ has a powerfull compiler, we can use it.
We can make sure that nobody creates
more than 1 instance of a given class, at
compile time.
Don’t over use it, it’s easy to learn, but
usually hides a design error in your code.
Sometimes is still necessary, and makes
your code better.
You need to use it in homework_7.
37
Singleton Pattern: How?
38
Singleton Pattern: How?
39
Singleton Pattern: How?
40
Singleton Pattern: What now?
41
Singleton Pattern: Completed
1 class Singleton {
2 private :
3 Singleton () = default ;
4 ~ Singleton () = default ;
5
6 public :
7 Singleton ( const Singleton &) = delete ;
8 void operator =( const Singleton &) = delete ;
9 static Singleton & GetInstance () {
10 static Singleton instance ;
11 return instance ;
12 }
13 };
42
Singleton Pattern: Usage
43
CRPT Pattern
1 # include <boost/core/ demangle .hpp >
2 using boost :: core :: demangle ;
3
4 template <typename T>
5 class Printable {
6 public :
7 explicit Printable () {
8 // Always print its type when created
9 cout << demangle ( typeid (T).name ()) << " created \n";
10 }
11 };
12
13 class Example1 : public Printable <Example1 > {};
14 class Example2 : public Printable <Example2 > {};
15 class Example3 : public Printable <Example3 > {};
44
CRPT Pattern
Usage:
1 int main () {
2 const Example1 obj1;
3 const Example2 obj2;
4 const Example3 obj3;
5 return 0;
6 }
Output:
1 Example1 Created
2 Example2 Created
3 Example3 Created
45
Suggested Video
Object Oriented Design
https://youtu.be/pTB0EiLXUC8
47
Suggested Video
Polymorphism
https://youtu.be/bP-Trkf8hNA
48
Must Watch
Raw Pointers: Skip min 30
https://www.youtube.com/watch?v=mIrOcFf2crk&t=1729s
0
Image Courtesy of Micriochip
49
References
Object Oriented Design
https://en.cppreference.com/w/cpp/language/derived_class
https://en.cppreference.com/w/cpp/language/virtual
https://en.cppreference.com/w/cpp/language/abstract_class
https://en.cppreference.com/w/cpp/language/override
https://en.cppreference.com/w/cpp/language/final
https://en.cppreference.com/w/cpp/language/friend
Type Conversion
https://en.cppreference.com/w/cpp/language/static_cast
https://en.cppreference.com/w/cpp/language/dynamic_cast
https://en.cppreference.com/w/cpp/language/reinterpret_cast
https://en.cppreference.com/w/cpp/language/const_cast
50
References: Patterns
Strategy Pattern
https://en.wikipedia.org/wiki/Strategy_pattern
https://refactoring.guru/design-patterns/strategy/cpp/example
https://stackoverflow.com/a/1008289/11525517
Singleton Pattern
https://en.wikipedia.org/wiki/Singleton_pattern
https://refactoring.guru/design-patterns/singleton/cpp/example
CRPT Pattern
https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
51