@pati_gallardo
C++ for Java Developers
@pati_gallardo Patricia Aas
JavaZone Academy - Tromsø 2018
Patricia Aas - Vivaldi Browser
Programmer - mainly in C++
Currently : Vivaldi Technologies
Previously : Cisco Systems, Knowit, Opera Software
Master in Computer Science - main language Java
Twitter : @pati_gallardo
Let’s Learn some Modern C++ (11-17)
@pati_gallardo
Don’t do This!
Hero * h = new Hero();
EVER
@pati_gallardo
- Hello World
- Values, Objects and Referring to
them
- Parameter Passing, Return
Values & Lambdas
- Memory : Lifetime & Ownership
- Structure : Classes and Structs
- Containers and Standard Types
@pati_gallardo
Your First Object
#include "Hero.h"
int main()
{
Hero h;
}
@pati_gallardo
Your First Program
#include <iostream>
#include <string>
int main()
{
std::string s("Wonder ");
std::cout << s << "Woman!";
}
@pati_gallardo
Includes - Java Import
Including your own headers
#include "Hero.h"
Including library headers
#include <string>
@pati_gallardo
Namespaces - Java Packages
namespace league {
class Hero {
};
}
@pati_gallardo
league::Hero h;
using namespace league;
Hero h;
Using namespace - Java Import static
@pati_gallardo
Using Namespace
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s("Wonder Woman!");
cout << s;
}
@pati_gallardo
Values, Objects and Referring to them
@pati_gallardo
Anything Can Be a Value
int main()
{
Hero b;
int meaning = 42;
auto pi { 3.14 };
std::string s = "Hi!";
std::mutex my_mutex;
}
@pati_gallardo
C++ Reference &
A C++ reference is not a Java pointer
It has to reference an object
It is never null
It can never reference another object
SAFE : Hero & h
@pati_gallardo
C++ Pointer *
A C++ pointer is not a Java pointer
It’s often called a “Raw Pointer”
It’s a raw memory address
UNSAFE : Hero * h
@pati_gallardo
C++ Value
In C++ everything is a value, even objects
When passed by value it is COPIED*
Can only pass-by-value if copying is supported*
SAFE : Hero h
* Sometimes the original value can be reused
@pati_gallardo
Range based For
vector<Hero> heroes;
for (auto & hero : heroes)
hero.rescue();
@pati_gallardo
Const : The Many Meanings class Hero {
public:
bool canFly() const;
void fly();
};
Hero superman;
deploy(superman);
void deploy(const Hero & h)
{
if (h.canFly()) // OK
h.fly(); //<-- ERROR
}
@pati_gallardo
const - Related to Final Variables in Java
Java
final Hero ptr; // ptr is final
C++
Hero * const ptr; // ptr is const
const Hero * ptr; // object is const
const Hero * const ptr; // object+ptr are const
@pati_gallardo
Immutable View Of An OBJECT
void crisis(const Hero & hero)
But the object is mutable - just not by you
Mark functions that don’t mutate as const
@pati_gallardo
Parameter Passing, Return Values & Lambdas
@pati_gallardo
Parameter Passing
Pass by const ref : const Hero & hero
Pass by reference : Hero & hero
Pass by value : Hero hero
Pass by pointer - be very careful
@pati_gallardo
Auto return type
auto meaning() { return 42; }
@pati_gallardo
Return by Value
Hero experiment() {
return Hero(); // return unnamed value
}
Hero experiment() {
Hero h;
return h; // return named value
}
@pati_gallardo
Return Value Optimization
Unnamed Return Value Optimization (RVO)
Named Return Value Optimization (NRVO)
@pati_gallardo
Slicing
Copying only parts of an object
class FlyingHero : public Hero {
int current_altitue = 0
}
FlyingHero superman;
Hero h = superman;
@pati_gallardo
Structured Bindings
std::tuple<int, int> point();
auto [x, y] = point();
@pati_gallardo
Lambda and Captures
auto meaning = [](){ return 42; };
auto life = 42;
auto meaning = [life](){ return life; };
auto meaning = [=](){ return life; };
auto meaning = [&](){ life++; return life;};
@pati_gallardo
Memory : Lifetime & Ownership
@pati_gallardo
Where is it?
Stack
Hero stackHero;
Heap
unique_ptr<Hero> heapHero =
make_unique<Hero>();
Hero * heapHero = new Hero();
@pati_gallardo
Stack - Similar to “Try With Resources”
Destroyed when exiting scope
Deterministic Garbage Collection
@pati_gallardo
Loving the Stack
#include <iostream>
#include <string>
using namespace std;
int main()
{
{
string s("Hello World!");
cout << s;
} // <- GC happens here!
}
@pati_gallardo
Hold a Value on the Stack that
Controls The Lifetime of Your Heap
Allocated Object
using namespace std;
{
unique_ptr<Hero> myHero =
make_unique<Hero>();
shared_ptr<Hero> ourHero =
make_shared<Hero>();
}
Smart Pointers
@pati_gallardo
Structure
@pati_gallardo
Class Declaration in Header File
Class Definition in Cpp File
Hero.h & Hero.cpp
A header is similar to an interface
Function declarations
Member variables
@pati_gallardo
Classes and Structs
@pati_gallardo
No Explicit Root Superclass
Implicitly defined member functions
Don’t redefine them if you don’t need to
The defaults are good
Rule-of-zero
(Zero except for the constructor)
@pati_gallardo
class B
{
public:
// Constructor
B();
// Destructor
~B();
// Copy constructor
B(const B&);
// Copy assignment op
B& operator=(const B&);
// Move constructor
B(B&&);
// Move assignment op
B& operator=(B&&);
};
Implicitly Defined
Functions
@pati_gallardo
All Classes Are Final by Default
By extension :
All methods are final by default
@pati_gallardo
Virtual Functions
Pure virtual - Interface
virtual void bootFinished() = 0;
Use override
void bootFinished() override;
@pati_gallardo
Multiple Inheritance is Allowed
Turns out
the ‘Diamond Problem’ is mostly academic
( and so is inheritance ;) )
@pati_gallardo
All Classes Are “Abstract”
Interface : only pure virtual methods
Abstract Class : some pure virtual methods
Plain Old Class : no pure virtual methods
@pati_gallardo
Structs
A C++ Struct is a Class
Where all members are public by default
@pati_gallardo
Static : The Many Meanings
“There can be only one”
Function in cpp file
Local variable in a function
Member / function in a class
@pati_gallardo
Static member / function in a Class
Pretty much the same as Java
@pati_gallardo
Static Function in a Cpp File
The function is local to the file
@pati_gallardo
Static Variable in a Function
- Global variable
- Only accessible in this function
- Same variable across calls
Hero heroFactory() {
static int num_created_heroes = 0;
++num_created_heroes;
return Hero();
} @pati_gallardo
Containers and Standard Types
@pati_gallardo
Use std::String - never char *
Use : std::string_view
Non-allocating, immutable string/substring
Note: Your project might have a custom string class
@pati_gallardo
Std::Vector Is Great
std::vector has great performance
Don’t use raw arrays
Prefer std::vector or std::array
@pati_gallardo
Use std::Algorithms
using namespace std;
vector<int> v { 1337, 42, 256 };
auto r =
find_if(begin(v), end(v), [](int i){
return i == 42;
});
@pati_gallardo
@pati_gallardo
Segmentation fault (core dumped)
Make Everyone Feel Safe To Be Themselves
@pati_gallardo
Vivaldi Swag
Patricia Aas, Vivaldi Technologies
@pati_gallardo
Photos from pixabay.com
@pati_gallardo

C++ for Java Developers (JavaZone Academy 2018)

  • 1.
  • 2.
    C++ for JavaDevelopers @pati_gallardo Patricia Aas JavaZone Academy - Tromsø 2018
  • 3.
    Patricia Aas - VivaldiBrowser Programmer - mainly in C++ Currently : Vivaldi Technologies Previously : Cisco Systems, Knowit, Opera Software Master in Computer Science - main language Java Twitter : @pati_gallardo
  • 4.
    Let’s Learn someModern C++ (11-17) @pati_gallardo
  • 5.
    Don’t do This! Hero* h = new Hero(); EVER @pati_gallardo
  • 6.
    - Hello World -Values, Objects and Referring to them - Parameter Passing, Return Values & Lambdas - Memory : Lifetime & Ownership - Structure : Classes and Structs - Containers and Standard Types @pati_gallardo
  • 7.
    Your First Object #include"Hero.h" int main() { Hero h; } @pati_gallardo
  • 8.
    Your First Program #include<iostream> #include <string> int main() { std::string s("Wonder "); std::cout << s << "Woman!"; } @pati_gallardo
  • 9.
    Includes - JavaImport Including your own headers #include "Hero.h" Including library headers #include <string> @pati_gallardo
  • 10.
    Namespaces - JavaPackages namespace league { class Hero { }; } @pati_gallardo
  • 11.
    league::Hero h; using namespaceleague; Hero h; Using namespace - Java Import static @pati_gallardo
  • 12.
    Using Namespace #include <iostream> #include<string> using namespace std; int main() { string s("Wonder Woman!"); cout << s; } @pati_gallardo
  • 13.
    Values, Objects andReferring to them @pati_gallardo
  • 14.
    Anything Can Bea Value int main() { Hero b; int meaning = 42; auto pi { 3.14 }; std::string s = "Hi!"; std::mutex my_mutex; } @pati_gallardo
  • 15.
    C++ Reference & AC++ reference is not a Java pointer It has to reference an object It is never null It can never reference another object SAFE : Hero & h @pati_gallardo
  • 16.
    C++ Pointer * AC++ pointer is not a Java pointer It’s often called a “Raw Pointer” It’s a raw memory address UNSAFE : Hero * h @pati_gallardo
  • 17.
    C++ Value In C++everything is a value, even objects When passed by value it is COPIED* Can only pass-by-value if copying is supported* SAFE : Hero h * Sometimes the original value can be reused @pati_gallardo
  • 18.
    Range based For vector<Hero>heroes; for (auto & hero : heroes) hero.rescue(); @pati_gallardo
  • 19.
    Const : TheMany Meanings class Hero { public: bool canFly() const; void fly(); }; Hero superman; deploy(superman); void deploy(const Hero & h) { if (h.canFly()) // OK h.fly(); //<-- ERROR } @pati_gallardo
  • 20.
    const - Relatedto Final Variables in Java Java final Hero ptr; // ptr is final C++ Hero * const ptr; // ptr is const const Hero * ptr; // object is const const Hero * const ptr; // object+ptr are const @pati_gallardo
  • 21.
    Immutable View OfAn OBJECT void crisis(const Hero & hero) But the object is mutable - just not by you Mark functions that don’t mutate as const @pati_gallardo
  • 22.
    Parameter Passing, ReturnValues & Lambdas @pati_gallardo
  • 23.
    Parameter Passing Pass byconst ref : const Hero & hero Pass by reference : Hero & hero Pass by value : Hero hero Pass by pointer - be very careful @pati_gallardo
  • 24.
    Auto return type automeaning() { return 42; } @pati_gallardo
  • 25.
    Return by Value Heroexperiment() { return Hero(); // return unnamed value } Hero experiment() { Hero h; return h; // return named value } @pati_gallardo
  • 26.
    Return Value Optimization UnnamedReturn Value Optimization (RVO) Named Return Value Optimization (NRVO) @pati_gallardo
  • 27.
    Slicing Copying only partsof an object class FlyingHero : public Hero { int current_altitue = 0 } FlyingHero superman; Hero h = superman; @pati_gallardo
  • 28.
    Structured Bindings std::tuple<int, int>point(); auto [x, y] = point(); @pati_gallardo
  • 29.
    Lambda and Captures automeaning = [](){ return 42; }; auto life = 42; auto meaning = [life](){ return life; }; auto meaning = [=](){ return life; }; auto meaning = [&](){ life++; return life;}; @pati_gallardo
  • 30.
    Memory : Lifetime& Ownership @pati_gallardo
  • 31.
    Where is it? Stack HerostackHero; Heap unique_ptr<Hero> heapHero = make_unique<Hero>(); Hero * heapHero = new Hero(); @pati_gallardo
  • 32.
    Stack - Similarto “Try With Resources” Destroyed when exiting scope Deterministic Garbage Collection @pati_gallardo
  • 33.
    Loving the Stack #include<iostream> #include <string> using namespace std; int main() { { string s("Hello World!"); cout << s; } // <- GC happens here! } @pati_gallardo
  • 34.
    Hold a Valueon the Stack that Controls The Lifetime of Your Heap Allocated Object using namespace std; { unique_ptr<Hero> myHero = make_unique<Hero>(); shared_ptr<Hero> ourHero = make_shared<Hero>(); } Smart Pointers @pati_gallardo
  • 35.
  • 36.
    Class Declaration inHeader File Class Definition in Cpp File Hero.h & Hero.cpp A header is similar to an interface Function declarations Member variables @pati_gallardo
  • 37.
  • 38.
    No Explicit RootSuperclass Implicitly defined member functions Don’t redefine them if you don’t need to The defaults are good Rule-of-zero (Zero except for the constructor) @pati_gallardo
  • 39.
    class B { public: // Constructor B(); //Destructor ~B(); // Copy constructor B(const B&); // Copy assignment op B& operator=(const B&); // Move constructor B(B&&); // Move assignment op B& operator=(B&&); }; Implicitly Defined Functions @pati_gallardo
  • 40.
    All Classes AreFinal by Default By extension : All methods are final by default @pati_gallardo
  • 41.
    Virtual Functions Pure virtual- Interface virtual void bootFinished() = 0; Use override void bootFinished() override; @pati_gallardo
  • 42.
    Multiple Inheritance isAllowed Turns out the ‘Diamond Problem’ is mostly academic ( and so is inheritance ;) ) @pati_gallardo
  • 43.
    All Classes Are“Abstract” Interface : only pure virtual methods Abstract Class : some pure virtual methods Plain Old Class : no pure virtual methods @pati_gallardo
  • 44.
    Structs A C++ Structis a Class Where all members are public by default @pati_gallardo
  • 45.
    Static : TheMany Meanings “There can be only one” Function in cpp file Local variable in a function Member / function in a class @pati_gallardo
  • 46.
    Static member /function in a Class Pretty much the same as Java @pati_gallardo
  • 47.
    Static Function ina Cpp File The function is local to the file @pati_gallardo
  • 48.
    Static Variable ina Function - Global variable - Only accessible in this function - Same variable across calls Hero heroFactory() { static int num_created_heroes = 0; ++num_created_heroes; return Hero(); } @pati_gallardo
  • 49.
    Containers and StandardTypes @pati_gallardo
  • 50.
    Use std::String -never char * Use : std::string_view Non-allocating, immutable string/substring Note: Your project might have a custom string class @pati_gallardo
  • 51.
    Std::Vector Is Great std::vectorhas great performance Don’t use raw arrays Prefer std::vector or std::array @pati_gallardo
  • 52.
    Use std::Algorithms using namespacestd; vector<int> v { 1337, 42, 256 }; auto r = find_if(begin(v), end(v), [](int i){ return i == 42; }); @pati_gallardo
  • 53.
  • 54.
    Make Everyone FeelSafe To Be Themselves @pati_gallardo
  • 55.
    Vivaldi Swag Patricia Aas,Vivaldi Technologies @pati_gallardo Photos from pixabay.com
  • 56.