SlideShare une entreprise Scribd logo
1  sur  81
Télécharger pour lire hors ligne
Introduction	to	C++
For	Those	Somewhat	Familiar	With	C
MPATE-GE	2617	C	Programming	for	Music	Technology	Lab
Jong	Wook	Kim
jongwook@nyu.edu
Things	To	Be	Covered
1.	History	and	Philosophy	of	C++
2.	Language	Features	Besides	Object-Orientation
3.	Object-Oriented	Programming	in	C++
4.	The	C++	Standard	Template	Library
5.	The	SOLID	Principles
6.	Examples	of	Using	C++	Libraries
7.	Summary
Things	To	Be	Covered
1.	History	and	Philosophy	of	C++
2.	Language	Features	Besides	Object-Orientation
3.	Object-Oriented	Programming	in	C++
4.	The	C++	Standard	Template	Library
5.	The	SOLID	Principles
6.	Examples	of	Using	C++	Libraries
7.	Summary
Background:	History	of	C
◦ In	1970,	Bell	Labs	needed	to	port	Unix	from	PDP-7	to	PDP-11
◦ Unix,	the	OS,	was	written	in	assembly	until	those	days
◦ The	developers	wanted	to	use	a	language,	but	there	was	no	suitable	one
◦ So	Ritchie	made	one	and	named	it	C	in	1972,	and	wrote	K&R	C	book	in	1978
◦ The	language	feature	has	been	largely	fixed	since	then
◦ C	became	the	language	of	choice	for	system	programming
◦ People	made	OS	using	C	(DOS	→	Windows,	BSD	→	MacOS	→	iOS,	Linux	→	Android)
◦ Because	it	is	so	simple	and	old,	it	is	so	fast
Ken	Thompson	and	Dennis	Ritchie PDP-7	(1965) PDP-11	(1970) K&R	C	(1978)
But	C	Hasn’t	Changed	for	Decades!
“Software	Crisis”	became	a	thing	circa	1970-1980
◦ Governments	and	companies	worked	on	large	software	projects	for	the	first	time
◦ Stock	exchange,	Healthcare,	Combat	support	system,	Criminal	intelligence,	etc.
◦ But	realized:	building	large-scale	software	is	totally	different	from	building	hardware	
◦ Projects	running	over-budget	and	over-time
◦ Software	being	very	inefficient	and	of	low	quality
◦ Code	difficult	to	maintain	(=	spaghetti	code)
◦ Projects	being	unmanageable
To	overcome	the	crisis,	new	methodologies	and	paradigms	emerged
◦ Software	Development	Process	/	Project	Management
◦ Version	Control	System
◦ Software	Quality
◦ Birth	of	“Software	Engineering”	as	a	discipline
Programming	Paradigms
C	follows	imperative,	procedural,	and	structured	programming	paradigm
◦ Write	commands	sequentially	and	organize	them	in	procedures
◦ Organize	associated	data	in	structures
After	the	crisis,	programmers	wanted	new	features	and	paradigms
◦ To	become	more	productive	in	programming,	especially	in	collaboration
◦ To	make	more	robust/efficient	programs	
◦ To	easily	develop	on	new	platforms	(web,	mobile)
◦ Object-Oriented	Programming	was	the	most	demanded	paradigm
C	is	fixed	in	features	and	paradigms,	so	people	created	more	languages
◦ C++	(’83),	ObjC (’84),	Python	(’91),	Lua (’93),	Java	(’95),	Ruby	(’95),	Scala	(’04),	Swift	(’14)
Object-Oriented	Programming
A	paradigm	that	designs	computer	programs	based	on	“objects”
◦ Contains	structured	data	(in	fields)	and	associated	behaviors	(in	methods)
◦ OOP	designs	a	program	in	terms	of	objects	interacting	with	one	another
◦ Keywords:	abstraction,	encapsulation,	inheritance,	polymorphism
Class
◦ A	popular	way	for	a	programming	language	to	implement	OOP
◦ Class:	specifies	the	data	format	and	available	procedures,	like	a	blueprint
◦ Instance:	a	realization	of	a	class,	with	specific	data	(=state).
◦ What	can	be	fields	and	methods	of:	Car,	Person,	Animal,	and	Radio?
C++	was	originally	called	“C	with	Classes”
◦ Class	=	struct with	associated	methods
◦ More	on	the	specific	syntax	later
Examples
class	Radio
- frequency:	Float
- volume:	Float
- playing:	Bool
- tuner: Tuner
- tune(frequency:	Float)
- set_volume(volume: Float)
- play()
- stop()
Examples
class	Radio
- playing:	Bool
- tuner: Tuner
- volume:	Float
- play()
- stop()
- tune(frequency:	Float)
- set_volume(volume: Float)
class	Tuner
circuit:	Circuit
tune(frequency:	Float)
get_audio():	Audio
class	Circuit
anthenna:	Anthenna
variable_resistor:	Resistor
set_resistance(ohm:	Float)
…
Examples
class	Mammal
- birthday:	Date
- weight:	Float
- breathe()
- eat(food:	Food)
class	Person
- name:	String
- study()
- work()
class	Dog
- name:	String
- bark()
- howl()
class	Cat
- name:	String
- purr()
- meow()
Software	Design	Patterns
Reusable	“pattern”	of	OOP	design	that	can	be	used	in	many	situations
Provides	a	solution	to	commonly	occurring	problems	in	software	design
Ways	of	organizing	relations	between	objects	in	order	to:
◦ Make	the	program	easy	to	read	and	maintain
◦ Implement	wanted	features	efficiently
◦ Maximize	reusability	of	the	code
Out	of	the	scope	of	this	class
◦ But	a	must-read	for	all	software	engineers
◦ One	of	them	will	be	covered	later	(iterator	pattern)
C++	as	a	Modernization	of	C
Created	by	Bjarne	Stroustrup in	1983,	ideas	originating	from	his	PhD	thesis
◦ Support	Object-Oriented	Programming	for	large-scale	software	development
◦ Have	to	be	fast	in	speed,	to	be	used	for	practical	purposes
◦ Mostly	a	superset	of	C,	because	general-purpose,	fast,	portable,	and	widely	used
Philosophy
◦ Driven	by	real-world	problems	and	should	be	useful	immediately
◦ User-create	types	need	to	have	the	same	performance	as	built-in	types
◦ Should	fully	support	any	programming	style	that	programmers	want
◦ Allowing	a	useful	feature	is	more	important	than	preventing	misuse	of	it
C++	actively	adds	support	for	new	features	and	paradigms
◦ While	C	remains	an	almost	unchanging,	minimal,	portable,	and	efficient	toolset
◦ A	new	Draft	International	Standard	in	March	2017,	to	become	C++17
Timeline	of	C++
1979:	Stroustrup starts	to	work	on	“C	with	Classes”	in	Bell	Labs
1983:	Renamed	to	“C++”
1985:	The	first	edition	of	<The	C++	Programming	Language>
1989:	C++	2.0	release
1998:	The	first	ISO	Standard	(C++98)
2003:	C++03,	bugfixes of	C++98
2011:	C++11,	a	major	revision
2014:	C++14,	bugfixes and	small	improvements	on	C++11
2017:	(planned)	C++17,	the	upcoming	major	revision
C++	was	such	a	hit
Date Estimated	Number	of	Users
Oct	1985 500
Oct	1986 2,000
Oct	1987 4,000
Oct	1988 15,000
Oct	1989 50,000
Oct	1990 150,000
Oct	1991 400,000
◦ Doubled	every	7.5	months in	1979-1991
◦ More	than	3	million	in	2004
What	Makes	It	So	Unique
The	only	language	that:
◦ Supports	modern	programming	paradigms	necessary	for	large-scale	development
◦ Supports	straightforward	and	zero-overhead	integration	with	C	programs	and	the	OS
◦ Still	maintains	close-to-metal	performance
◦ (Feasible	alternatives	came	up	only	very	recently,	like	Rust,	Go,	Swift)
Many	performance-critical	large-scale	applications	are	built	in	C++
◦ Windows,	MacOS,	Android,	iOS,	and	many	Linux	distributions
◦ Almost	all	major	PC/console	games
◦ Almost	all	browsers:	Google	Chrome,	Safari,	Internet	Explorer,	Edge,	Firefox
◦ Almost	all	Adobe	products:	Photoshop,	Illustrator,	Premiere,	Acrobat
◦ Almost	all	DAW	software:	Logic	Pro,	Pro	Tools,	Adobe	Audition,	Ableton Live
◦ All	major	C/C++	compilers:	GCC,	Visual	C++,	Clang
◦ Core	of	many	deep	learning	libraries:	Tensorflow,	Caffe,	MXNet
Things	To	Be	Covered
1.	History	and	Philosophy	of	C++
2.	Language	Features	Besides	Object-Orientation
3.	Object-Oriented	Programming	in	C++
4.	The	C++	Standard	Template	Library
5.	The	SOLID	Principles
6.	Examples	of	Using	C++	Libraries
7.	Summary
Hello	World
◦ C++	Headers	are	without	the	.h extension
◦ using namespace std;
◦ A	namespace	that	contains	all	features	of	the	C++	standard	library
◦ No	need	to	prefix	functions	with	library	names
◦ <iostream> provides	console	input/output	via	cin and	cout
◦ Also	endl,	which	outputs	a	newline	and	flushes	the	stream
◦ No	need	to	use	the	format	string
◦ The	shift	operator	<< has	a	different	meaning	here	– Operator	Overloading
Namespaces
◦ Either	write	using namespace std; or	use	the	prefix	std::
◦ Can	be	nested	to	multiple	depths
◦ Helps	organizing	functions,	variables,	and	classes
std::cin
◦ >>	operator	overloading	,	for	console	input
◦ No	need	to	use	format	strings,	again
std::string
◦ Is	a	“class”	provided	by	the	C++	Standard	Library
◦ Start	by	assigning	a	string	literal	to	a	string	variable,	or	in	C++14,	"hello"s
◦ A	lot	safer	than	the	C	way,	manipulating	strings	only	in	char*
Function	Overloading
◦ The	actual	function	called	is	dependent	on	the	types	of	the	arguments
◦ Called	“ad-hoc	polymorphism”	by	some	people
New	&	Delete
◦ C	version:	relies	on	library	functions
◦ Size	calculation
◦ Allocation	with	malloc()
◦ Type	casting
◦ Initialization
◦ Deallocation	with	free()
◦ C++	version:	a	language	feature
◦ All	of	the	first	4	in	one	line
◦ Deallocation	with	delete
New	[]	&	Delete	[]
◦ Again,	no	need	to	calculate	size	and	typecast	manually
◦ new [] and	delete[] have	to	match
Templates
◦ Template	functions	and	template	classes	are	“realized”	according	to	types
◦ One	implementation	for	many	types,	improving	reusability	of	code
◦ For	example:	linked	list	of	type	T,	hash	map	from	type	K	to	V
References
◦ Acts	like	a	pointer,	looks	like	a	variable
◦ Avoids	pointer	insanity	(to	some	degree)
◦ Cannot	be	NULL,	which	is	a	good	thing
◦ Necessary	for	using	some	C++	features	that	we	will	not	go	into	detail
◦ Operator	overloading,	copy	constructor,	move	constructor
Exception	Handling
Most	C	functions	use	a	special	
return	value	to	indicate	an	error
◦ -1,	errno,	etc.,	usually	a	number
◦ Inconsistent	codes	per	function
◦ Cannot	return	other	types
C++	encourages	using	exceptions
◦ Throw	any	variable	anywhere
◦ Across	function	calls
◦ Catch	according	to	the	type
◦ Return	value	can	be	result	type
◦ Fail-fast	on	the	first	error
Controversy	exists	on	using	them
C++11:	Lambdas
◦ A	function	can	be	created	and	passed	to	another	function
◦ Cleaner	than	using	function	pointers
◦ Higher-order	Function:	a	function	that	accepts	a	function(s)	as	its	parameters
◦ An	element	of	“Functional	Programming”	paradigm
C++11/14:	Type	Deduction
◦ Type	declaration	is	not	necessary	wherever	compiler	can	deduce	the	type
◦ Useful	when	stating	the	type	is	redundant,	too	obvious,	or	too	verbose
More	Non-OOP	Features
No	Need	to	typedef struct
Single-line	comments	using	//
Boolean	type	bool is	a	built-in	type
◦ no	need	to	include	stdbool.h
Default	arguments:	
◦ void foo(int a = 3) { ...
Inline	functions
◦ Compiler	puts	the	content	in	the	caller,	not	making	a	function	actually
nullptr instead	of	NULL which	is	just	0
◦ Which	is	number,	not	a	pointer,	thus	confusing	and	dangerous
Summary	So	Far
Added	features	to	write	programs	in	safer	and	more	convenient	ways
Fixing	common	pain	points	and	incorporating	latest	paradigms	quickly
At	the	cost	of	having	to	continuously	learn	new	concepts	and	paradigms
Things	To	Be	Covered
1.	History	and	Philosophy	of	C++
2.	Language	Features	Besides	Object-Orientation
3.	Object-Oriented	Programming	in	C++
4.	The	C++	Standard	Template	Library
5.	The	SOLID	Principles
6.	Examples	of	Using	C++	Libraries
7.	Summary
Reminder:
Object-Oriented	Programming
A	paradigm	that	designs	computer	programs	based	on	“objects”
◦ Contains	structured	data	(in	fields)	and	associated	behaviors	(in	methods)
◦ OOP	designs	a	program	in	terms	of	objects	interacting	with	one	another
◦ Keywords:	abstraction,	encapsulation,	inheritance,	polymorphism
Class
◦ A	popular	way	for	a	programming	language	to	implement	OOP
◦ Class:	specifies	the	data	format	and	available	procedures,	like	a	blueprint
◦ Instance:	a	realization	of	a	class,	with	specific	data	(=state).
C++	was	originally	called	“C	with	Classes”
◦ Class	=	struct with	associated	methods
◦ More	on	the	specific	syntax	later
Class	=	Data	+	Behaviors
=	Struct +	methods
Methods	can	be	added	to	a	struct
◦ Also	known	as	member	functions
◦ Should	be	associated	with	the	struct’s data
◦ Therefore	the	task	is	a	“duty”	of	this	class
◦ Yes,	A	struct with	methods	is	now	a	class
Terms
Class	(which	is	a	Type) Field
Member	Variable
Method
Member	Function
Constructor
In	the	previous	example,	the	initialization	of	
Person’s	fields	was	done	in	main()
◦ But	organizing	its	fields	should	be	Person’s	duty
Constructor	does	that	job
◦ Called	only	as	soon	as	the	instance	is	created
◦ Parameters	=	any	data	required	for	initialization
There	can	be	more	than	one	constructors
◦ One	of	them	must	be	called,	otherwise	compile	fails
Can	be	called	during	declaration
◦ auto p = new Person(“Doe”) also	works
An	Even	Better	Constructor
Passes	the	argument	to	the	string
name’s	constructor.
◦ Which	initializes	the	string	class	with	
the	given	argument
◦ The	no-agrument constructor	of	
string name is	never	called.
In	main(),	Person	is	reused
◦ Providing	an	abstraction
◦ By	grouping	data (name)	and	behavior
(printing	name)	inside	an	object.
Encapsulation:	access	specifier
Fields	and	methods	can	have	“access	specifiers”,	e.g.	public: or	private:
Encapsulation:	accessor
Accessor	(or	getter)	method
◦ Simply	returns	a	field
◦ Allows	others	to	see	the	value
◦ But	not	mutate	the	value
◦ Read-only	for	others,	full	access	for	self
Abstraction	to	users	of	the	class	Person
◦ Only	need	to	know
◦ The	methods	and	constructors	of	the	class
◦ No	need	to	know
◦ Any	private	fields	or	methods
struct vs	class
The	only	difference	is	the	default	access	level
◦ Members	of	struct are	public	by	default
◦ Members	of	class are	private	by	default
In	C,	struct was	just	a	data	bundle
◦ That	can	be	manipulated	from	anywhere
C++	added	methods	to	struct for	class
◦ struct members	have	to	be	public	by	default
◦ To	retain	compatibility	with	C
◦ But	C++	liked	encapsulation	so	much!
◦ So	they	made	class members	private	by	default
Rule	of	thumb
◦ Use	struct for	simple	data	storage
◦ May	have	minimal	logic	on	data	validation,	etc.
◦ Use	class for	anything	more	than	that
Inheritance	– Basics
Derived	class	inherits	base	class
◦ Student	=	Derived,	Person	=	Base
◦ Derived	class	has	all	members	of	Base
Makes	it	easier	to
◦ Reuse	the	functionality	of	the	base	class
Inheritance	– Pet	Example
talk() inherited	to	Dog and	Cat:
sound() overridden in	Dog and	Cat
If	base	class	has	a	constructor
◦ Must	call	when	constructing	derived
◦ Unless	base	constructor	is	zero-argument
Use	virtual method	if	inheriting
◦ Required	for	polymorphism
Polymorphism
The	pets	example	continued:
◦ void print(Pet &) does	not	know	anything	
about	the	two	derived	classes
◦ Compiler	does	not	consider	the	derived	classes	at	all,	
while	compiling	this	function
◦ Still	the	corresponding	sounds	gets	printed.
◦ Because	the	exact	method	to	be	called	is	determined	
during	the	run-time
◦ virtual keyword	is	required	for	this	process
◦ Single	interface	talk()	can	invoke	many	different	
implementations	depending	on	the	type
◦ Thus	called	“polymorphic”
Pure	Virtual	Methods
◦ We	didn’t	need	the	function	returning	“???”,	and	we	can	just	put	=0 instead
◦ This	method	has	no	definition,	and	is	called	a	pure	virtual	method
◦ A	class	with	a	pure	virtual	method	is	called	an	abstract	class,	as	opposed	to	a	concrete	class
◦ An	abstract	class	cannot	be	instantiated	directly,	and	derived	types	must	be	used
◦ A	derived	type	must	override	all	pure	virtual	methods,	otherwise	it	becomes	abstract	too
Access	Specifier:	protected
Protected	members	are	accessible	only	from	a	derived	class
public protected private
this	class Yes Yes Yes
derived	classes Yes Yes No
elsewhere Yes No No
Destructor
Class	may	manage	resources
◦ e.g.	files,	connections	to	web
◦ malloc’ed memory	buffer
◦ Resource	handles,	like	SNDFILE	*
◦ that	have	to	be	cleaned	up	/	closed
Destructor	is	responsible	of
◦ Safely	closing	any	open	resources
Called	when	object’s	lifetime	ends
◦ A	local	variable	gets	out	of	scope
◦ An	object	is	delete’ed
◦ Program	exits	(global	variables)
RAII
Acronym	for	Resource	Acquisition	Is	Initialization
Resource	usage	is	encapsulated	in	the	lifetime	of	an	object
◦ Constructor acquires	the	resource	or	throws	an	exception	when	it	cannot
◦ Destructor releases	the	resource	and	never	throws	exceptions
Using	the	resource	is	always	through	an	instance	of	a	RAII-class
◦ Guarantees	that	the	resource	is	available,	whenever	an	instance	is	reachable
◦ Prevents	unwanted	access	to	resources	after	being	released
◦ Makes	sure	to	release	the	resource	properly
To	make	the	most	out	of	RAII,
◦ Limit	the	scope	of	a	variable	to	where	it	is	actually	being	used
◦ When	it	is	dynamically	allocated,	be	sure	to	delete
std::fstream
A	good	example	of	RAII
◦ File	is	closed	as	fstream exits	the	scope
A	good	example	of	polymorphism
The	same	function	print() works	on	both
console	output	and	file	output
Replaces	fopen/fprintf/fclose
Summary	of	OOP	Concepts
Abstraction
◦ In	many	levels,	of	data	(encapsulation),	hierarchy	(inheritance),	behavior	(polymorphism)	
Encapsulation
◦ Information	hiding,	with	private,	protected,	or	public access	specifiers
◦ Provide	users	only	what	they	need	to	know,	to	make	it	easier	to	use	and	prevent	misuse
Inheritance
◦ Subclass	can	extend	base	class	inheriting	its	data	and	behavior
◦ Can	build	a	hierarchy	of	classes,	representing	“is	a”	relationships
Polymorphism
◦ Behavior	of	a	method	can	be	different,	depending	on	the	subclass
Things	To	Be	Covered
1.	History	and	Philosophy	of	C++
2.	Language	Features	Besides	Object-Orientation
3.	Object-Oriented	Programming	in	C++
4.	The	C++	Standard	Template	Library
5.	The	SOLID	Principles
6.	Examples	of	Using	C++	Libraries
7.	Summary
The	Standard	Template	Library
In	C,	the	closest	thing	that	we	had	to	a	data	structure	is	array	of	structs
So	we	had	to	implement	our	own	as	we	go
◦ Queue	of	visited	cells	for	breadth-first	search	in	a	maze
◦ Hash	map	for	searching	phone	book	by	the	last	name
◦ Linked	list	of	phone	book	entries,	using	chain	parameter
However,	the	implementation	had	to	be	specific	to	the	element	type
◦ There	is	void *,	but	it	throws	away	any	type	information	and	safety
STL allows	a	generic	implementation	regardless	of	types,	using	templates
◦ e.g.	queue<Cell>, map<string, PhoneBookEntry>, list<PhoneBookEntry>
Containers
There	are	a	lot	of	data	structures	made	for	storing	collection	of	data
◦ Sequence	containers
◦ vector,	array,	list,	forward_list
◦ Each	has	different	efficiency	for	random	access,	insertion,	and	deletion	
◦ Sequence	container	adapters
◦ stack,	queue,	priority_queue
◦ Ordered	associative	containers
◦ set,	map,	multiset,	multimap
◦ Unordered	associative	(hash)	containers
◦ unordered_set,	unordered_map,	unordered_multiset,	unordered_multimap
In	C,	had	to	go	with	own	implementation	always
◦ There	is	no	de-facto	standard	containers	library	or	something	close	to	that
◦ Partly	due	to	the	lack	of	templates
std::vector<T>
Like	a	regular	array,	but	resizes	dynamically	as	needed
Capacity	can	be	given	in	constructor	or	by	reserve()
Suitable	for	append-only	seq of	unknown	length	with	index	access
std::array<T, N>
Contains	a	fixed-length	array
◦ Same	performance	as	C	array,	as	it	does	not	dynamically	allocate	memory
Conforms	with	other	STL	containers
◦ Supports	size(),	front(),	back() etc.
◦ Can	produce	iterators,	to	be	covered	later
std::list<T>
Implementation	of	doubly-linked	list
Compared	to	vector/array
◦ Faster	insertion	in	the	middle
◦ No	spurious	delay	for	insertion	due	to	reallocation
◦ Same	O(n)	complexity	for	sequential	traverse
◦ Relatively	inefficient	memory	usage	overall
◦ O(n)	random	access,	as	opposed	to	vector/array’s	O(1)
std::forward_list<T>
Does	not	have	“backwards”	link
◦ Can	only	traverse	from	the	beginning,	which	is	enough	for	many	use	cases
◦ Same	time	complexity	for	insertion,	deletion,	traversal,	random	access
◦ Slightly	higher	memory	efficiency
◦ No	size(),	back(),	push_front()	available	– have	to	use	iterators
std::stack<T>
First-in,	last-out	data	structure
◦ push(),	pop(),	top()
◦ Can	optionally	replace	the	back-end	data	structure
◦ Anything	that	supports	push_back(),	pop_back(),	and	back().
std::queue<T>
First-in,	first-out	data	structure
◦ push(),	pop(),	top()
◦ Can	optionally	replace	the	back-end	data	structure
std::priority_queue<T>
Constant-time	lookup	of	the	largest	element
Other	criteria	can	be	given	as	the	third	template	argument
std::set<T>
Contains	a	set	of	unique	items
◦ Efficient	for	checking	existence	of	items,	number	of	unique	items
std::set<T>:	based	on	binary	search	tree
◦ Automatically	sorts	the	items,	logarithmic	time	lookup
std::unordered_set<T>:	based	on	hash
◦ Not	ordered,	constant	time	lookup
std::map<K, V>
Associative	container	– retrieve	a	value	associated	with	given	key
std::map<K,	V>:	based	on	binary	search	tree
◦ Automatically	sorts	the	items	based	on	key,	logarithmic	time	lookup
std::unordered_map<K,	V>:	based	on	hash
◦ Not	ordered,	constant	time	lookup
Iterators
A	generalization	of	pointer	for	traversing	containers
◦ Used	as	a	common	interface	for	different	container	types
Iterators:	range-based	for loop
Having	a	unified	interface	for	traversing	containers	enables	this:
One	less	variable	to	think	about	(the	index)
◦ One	less	source	of	possible	bugs
Iterators:	find()
Searches	a	container	and	returns	an	iterator	pointing	to	the	found	item
◦ or	container.end() if	not	found
std::find() performs	the	same	job
◦ Also	usable	for	containers	with	non-constant	time	lookup
Algorithms
std::find() is	one	of	the	functions	in	the	algorithms	library
In	C,	there	were	only	two:	qsort and	bsearch
Curated	list	of	C++	algorithms
◦ for_each,	count,	find,	search
◦ copy,	fill,	transform,	generate,	swap,	reverse,	rotate,	shuffle,	unique
◦ is_sorted,	sort,	partial_sort,	stable_sort,	nth_element
◦ is_heap,	make_heap,	push_heap,	pop_heap
◦ max,	max_element,	min,	min_element,	minmax,	minmax_element
◦ is_permutation,	next_permutation,	prev_permutation
◦ accumulate,	inner_product,	adjacent_difference,	partial_sum,	reduce
Algorithms:	for_each
Yet	another	way	of	visiting	all	elements	in	a	container
Range-based-for	is	shorter,	but	useful	when	we	want	to:
◦ Apply	a	function	to	a	partial	range
◦ Apply	a	function	that	is	already	implemented	somewhere	else
Algorithms:	Permutations
Prints	all	possible	permutations	in	a	range	of	items
std::shared_ptr
Dynamically	allocated	objects	are	useful	when	an	instance	is	‘shared’
◦ So	having	it	as	a	local	variable	is	not	very	feasible
But	having	to	remember	and	control	exactly	when	to	delete them	is	difficult!
◦ Difficult	also	means	dangerous
◦ Continuing	the	“making	it	harder	to	shoot	yourself	in	the	foot”	philosophy
◦ References	to	an	object	is	counted,	and	gets	deleted	automatically	when	it	reaches	0
◦ Can	be	used	just	like	regular	pointers
Similar:	std::unique_ptr
◦ Instead	of	reference	counting,
only	one	pointer	can	own	the	access
Things	To	Be	Covered
1.	History	and	Philosophy	of	C++
2.	Language	Features	Besides	Object-Orientation
3.	Object-Oriented	Programming	in	C++
4.	The	C++	Standard	Template	Library
5.	The	SOLID	Principles
6.	Examples	of	Using	C++	Libraries
7.	Summary
The	SOLID	Principles
A	mnemonic	acronym	for	5	basic	principles	of	OOP	design
Single	Reponsibility Principle
◦ A	class	should	have	only	a	single	responsibility
Open/Closed	Principle
◦ Software	entities	should	be	open	for	extension,	but	closed	for	modification
Liskov Substitution	Principle
◦ Objects	should	be	replaceable	with	a	subtype	without	altering	the	correctness
Interface	Segregation	Principle
◦ Many	client-specific	interfaces	are	better	than	one	general-purpose	interface
Dependency	Inversion	Principle
◦ One	should	depend	upon	abstractions,	not	concretions
Single	Responsibility	Principle
A	class	should	have	only	one	responsibility	which
◦ Should	be	entirely	encapsulated	by	the	class
◦ Should	be	apparent	by	looking	at	the	name
◦ Robert	C	Martin:	“A	class	should	have	only	one	reason	to	change”
Good	example
◦ A	report	printer	program	may	have	two	reasons	to	change,	thus	has
◦ A	class	representing	the	content	of	a	report
◦ A	class	representing	the	format	of	a	report
Bad	example
◦ There	is	only	one	big	class	that	basically	have	all	functions	of	a	program
◦ Just	like	C,	but	inside	a	class!
Open-Closed	Principle
Open	for	extension
◦ The	behavior	of	a	base	class	can	be	extended	(usually	via	inheritance)
Closed	for	modification
◦ Modification	of	the	base	class	is	not	desired
Liskov Substitution	Principle
Code	written	for	a	base	class	should	also	work	when	an	instance	of	a	derived	class
Interface	Segregation	Principle
Interfaces
◦ Usually	means	a	class	with	only	pure	virtual	functions
C++	Supports	multiple	inheritance
◦ Segregate	interfaces	to	the	simplest	unit
◦ Multiple	inheritance	for	a	versatile	class
Dependency	Inversion	Principle
main()
Task1
Subtask1-1
Subtask1-2
Task2
Subtask2-1
Subtask2-2
Task3
Subtask3-1
Subtask3-2
Things	To	Be	Covered
1.	History	and	Philosophy	of	C++
2.	Language	Features	Besides	Object-Orientation
3.	Object-Oriented	Programming	in	C++
4.	The	C++	Standard	Template	Library
5.	The	SOLID	Principles
6.	Examples	of	Using	C++	Libraries
7.	Summary
PortAudio C++
PortAudio C++	Continued
Eigen
Fast	linear	algebra	library	entirely	based	on	templates
◦ brew install eigen
Other	Notable	C++	Libraries
Things	To	Be	Covered
1.	History	and	Philosophy	of	C++
2.	Language	Features	Besides	Object-Orientation
3.	Object-Oriented	Programming	in	C++
4.	The	C++	Standard	Template	Library
5.	The	SOLID	Principles
6.	Examples	of	Using	C++	Libraries
7.	Summary
Summary
C++	as	a	whole	package
◦ Provides	tons	of	modern	facilities	for	programmers	to	utlize
◦ Object-Oriented	Programming
◦ Functional	Programming
◦ Generic	Programming
◦ Don’t	be	scared,	just	pick	any	subset	you	would	like
◦ More	library	options	that	will	help	you	explore	ideas	
◦ In	some	sense,	C++	is	the	final	boss	of	programming	languages

Contenu connexe

Similaire à Introduction to C++ for Those Somewhat Familiar with C

C & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTREC & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTREjatin batra
 
Evolution of programming languages
Evolution of programming languagesEvolution of programming languages
Evolution of programming languagesNitin Kumar Kashyap
 
L1-L2.Introduction to Programming and Python Basics.pptx
L1-L2.Introduction to Programming and Python Basics.pptxL1-L2.Introduction to Programming and Python Basics.pptx
L1-L2.Introduction to Programming and Python Basics.pptxDeepjyotiChoudhury4
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingSivant Kolhe
 
Prepared by: john reynald lordan
Prepared by: john reynald lordanPrepared by: john reynald lordan
Prepared by: john reynald lordanforveryou19
 
Python.pptx
Python.pptxPython.pptx
Python.pptxabclara
 
C++ history session 00 history
C++ history session 00   historyC++ history session 00   history
C++ history session 00 historyArun Prakash
 
History of c programming language.
History of c programming language.History of c programming language.
History of c programming language.Md Khalid Hasan
 
An introduction to go programming language
An introduction to go programming languageAn introduction to go programming language
An introduction to go programming languageTechnology Parser
 
C++ vs C#
C++ vs C#C++ vs C#
C++ vs C#sudipv
 
Programing fundamentals with C++
Programing fundamentals with C++Programing fundamentals with C++
Programing fundamentals with C++farooq2016
 

Similaire à Introduction to C++ for Those Somewhat Familiar with C (20)

C & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTREC & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
 
Evolution of programming languages
Evolution of programming languagesEvolution of programming languages
Evolution of programming languages
 
History of c
History of cHistory of c
History of c
 
C, Objective C & C++ History
C, Objective C & C++ HistoryC, Objective C & C++ History
C, Objective C & C++ History
 
L1-L2.Introduction to Programming and Python Basics.pptx
L1-L2.Introduction to Programming and Python Basics.pptxL1-L2.Introduction to Programming and Python Basics.pptx
L1-L2.Introduction to Programming and Python Basics.pptx
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Prepared by: john reynald lordan
Prepared by: john reynald lordanPrepared by: john reynald lordan
Prepared by: john reynald lordan
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
C++ history session 00 history
C++ history session 00   historyC++ history session 00   history
C++ history session 00 history
 
C language By OmishaTech
C language By OmishaTechC language By OmishaTech
C language By OmishaTech
 
Evalution about programming language part 1
Evalution about programming language part 1Evalution about programming language part 1
Evalution about programming language part 1
 
Lecture 1- History of C Programming
Lecture 1- History of C Programming Lecture 1- History of C Programming
Lecture 1- History of C Programming
 
History of c programming language.
History of c programming language.History of c programming language.
History of c programming language.
 
An introduction to go programming language
An introduction to go programming languageAn introduction to go programming language
An introduction to go programming language
 
sheet 1.docx
sheet 1.docxsheet 1.docx
sheet 1.docx
 
P1 2017 python
P1 2017 pythonP1 2017 python
P1 2017 python
 
P1 2018 python
P1 2018 pythonP1 2018 python
P1 2018 python
 
C++ vs C#
C++ vs C#C++ vs C#
C++ vs C#
 
Ch1 Introducing C
Ch1 Introducing CCh1 Introducing C
Ch1 Introducing C
 
Programing fundamentals with C++
Programing fundamentals with C++Programing fundamentals with C++
Programing fundamentals with C++
 

Plus de Jong Wook Kim

A Short Introduction to Generative Adversarial Networks
A Short Introduction to Generative Adversarial NetworksA Short Introduction to Generative Adversarial Networks
A Short Introduction to Generative Adversarial NetworksJong Wook Kim
 
자바 전문가를 위한 스칼라 프로그래밍 언어
자바 전문가를 위한 스칼라 프로그래밍 언어자바 전문가를 위한 스칼라 프로그래밍 언어
자바 전문가를 위한 스칼라 프로그래밍 언어Jong Wook Kim
 
No More "sbt assembly": Rethinking Spark-Submit using CueSheet
No More "sbt assembly": Rethinking Spark-Submit using CueSheetNo More "sbt assembly": Rethinking Spark-Submit using CueSheet
No More "sbt assembly": Rethinking Spark-Submit using CueSheetJong Wook Kim
 
Crash Course on Graphical models
Crash Course on Graphical modelsCrash Course on Graphical models
Crash Course on Graphical modelsJong Wook Kim
 
dart:async로 맛보는 Functional Reactive Programming
dart:async로 맛보는 Functional Reactive Programmingdart:async로 맛보는 Functional Reactive Programming
dart:async로 맛보는 Functional Reactive ProgrammingJong Wook Kim
 
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기Jong Wook Kim
 

Plus de Jong Wook Kim (7)

A Short Introduction to Generative Adversarial Networks
A Short Introduction to Generative Adversarial NetworksA Short Introduction to Generative Adversarial Networks
A Short Introduction to Generative Adversarial Networks
 
자바 전문가를 위한 스칼라 프로그래밍 언어
자바 전문가를 위한 스칼라 프로그래밍 언어자바 전문가를 위한 스칼라 프로그래밍 언어
자바 전문가를 위한 스칼라 프로그래밍 언어
 
No More "sbt assembly": Rethinking Spark-Submit using CueSheet
No More "sbt assembly": Rethinking Spark-Submit using CueSheetNo More "sbt assembly": Rethinking Spark-Submit using CueSheet
No More "sbt assembly": Rethinking Spark-Submit using CueSheet
 
Crash Course on Graphical models
Crash Course on Graphical modelsCrash Course on Graphical models
Crash Course on Graphical models
 
dart:async로 맛보는 Functional Reactive Programming
dart:async로 맛보는 Functional Reactive Programmingdart:async로 맛보는 Functional Reactive Programming
dart:async로 맛보는 Functional Reactive Programming
 
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
 
Skip List
Skip ListSkip List
Skip List
 

Dernier

Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 

Dernier (20)

Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 

Introduction to C++ for Those Somewhat Familiar with C