SlideShare a Scribd company logo
OOP in C++ Ganesh Samarthyam
ganesh@codeops.tech
โ€œThere are two ways of
constructing a software
design: One way is to make
it so simple that there are
obviously no de๏ฌciencies,
and the other way is to make
it so complicated that there
are no obvious de๏ฌciencies.
The ๏ฌrst method is far more
dif๏ฌcult.โ€
C. A. R. Hoare
Example of beautiful design
int arr[] = {1, 4, 9, 16, 25}; // some values
// find the first occurrence of 9 in the array
int * arr_pos = find(arr, arr + 4, 9);
std::cout<< โ€œarray pos = โ€œ<< arr_pos - arr << endl;
vector<int> int_vec;
for(int i = 1; i <= 5; i++)
int_vec.push_back(i*i);
vector<int>::iterator vec_pos = find (int_vec.begin(), int_vec.end(), 9);
std::cout<< โ€œvector pos = โ€œ<< (vec_pos - int_vec.begin());
"The critical design tool for software development
is a mind well educated in design principles"
- Craig Larman
Robert C. Martin
Formulated many principles and described
many other important principles
Michael Feathers
Michael Feathers coined the acronym
SOLID in 2000s to remember ๏ฌrst ๏ฌve of the
numerous principles by Robert C. Martin
SOLID principles
S
Single Responsibility
Principle
Every object should have a single responsibility and
that should be encapsulated by the class
O Open Closed Principle
Software should be open for extension, but closed for
modification
L
Liskovโ€™s Substitution
Principle
Any subclass should always be usable instead of its
parent class
I
Interface Segregation
Principle
Many client specific interfaces are better than one
general purpose interface
D
Dependency Inversion
Principle
Abstractions should not depend upon details. Details
should depend upon abstractions
3 principles behind patterns
Design'principles'
behind'pa0erns'
Program'to'an'
interface,'not'to'an'
implementa7on''
Favor'object'
composi7on''
over'inheritance'
Encapsulate'what'
varies'
Boochโ€™s fundamental principles
Principles*
Abstrac/on*
Encapsula/on*
Modulariza/on*
Hierarchy*
How to apply principles in practice?
Design principles
Code
How to bridge
the gap?
Why care about refactoring?
As an evolving program is
continually changed, its
complexity, reflecting
deteriorating structure,
increases unless work is done
to maintain or reduce it
- Lehman's law of Increasing Complexity
What is refactoring?
Refactoring (noun): a change
made to the internal structure of
software to make it easier to
understand and cheaper to
modify without changing its
observable behavior
Refactor (verb): to restructure
software by applying a series
of refactorings without
changing its observable
behavior
What are smells?
โ€œSmells'are'certain'structures'
in'the'code'that'suggest'
(some4mes'they'scream'for)'
the'possibility'of'refactoring.โ€''
Granularity of smells
Architectural+
+
Cyclic&dependencies&between&modules&
Monolithic&modules&&
Layering&viola9ons&(back&layer&call,&skip&layer&call,&ver9cal&layering,&
etc)&
Design+
+
God&class&
Refused&bequest&&
Cyclic&dependencies&between&classes&
Code+(implementa6on)++
+
Internal&duplica9on&(clones&within&a&class)&&
Large&method&&
Temporary&๏ฌeld&&
Procedural code
#include <string>
#include <iostream>
using namespace std;
enum Animal { rat, pig, frog };
string talk(enum Animal animal) {
switch(animal) {
case rat: return "squeak";
case pig: return "oink";
case frog: return "ribbit";
default: return "unrecognized case value";
}
}
int main() {
enum Animal animal = pig;
cout << talk(animal) << endl;
}
Object oriented code
#include <string>
#include <iostream>
using namespace std;
class Animal {
public:
virtual string talk() = 0;
};
class Rat : public Animal {
public:
string talk() override { return "squeak"; }
};
class Pig : public Animal {
public:
string talk() override { return "oink"; }
};
class Frog : public Animal {
public:
string talk() override { return "ribbit"; }
};
int main() {
Pig pig;
Animal &animal = pig;
cout << animal.talk() << endl;
}
Functional code
#include <iostream>
using namespace std;
int main() {
auto rat = []() { return "squeak"; };
auto pig = []() { return "oink"; };
auto frog = []() { return "ribbit"; };
auto animaltalk = pig;
cout << animaltalk() << endl;
}
Generic code
#include <string>
#include <iostream>
using namespace std;
enum Animal {
rat, pig, frog
};
typedef const char * cstring;
template <enum Animal animal>
struct talk {
static constexpr cstring value = "undefined";
};
template <>
struct talk<rat> {
static constexpr cstring value = "squeak";
};
template <>
struct talk<pig> {
static constexpr cstring value = "oink";
};
template <>
struct talk<frog> {
static constexpr cstring value = "ribbit";
};
int main() {
cout << talk<pig>::value << endl;
}
Object Oriented Design
- Essentials
Inheritance vs. composition
โ– A common base class means common behaviour to its
derived types
โ– Public inheritance means โ€œis-aโ€ relationship
โ– Private inheritance means โ€œis-implemented-in-terms-ofโ€
โ– Composition means โ€œhas-aโ€ or โ€œis-implemented-in-
terms-ofโ€
Virtual or non-virtual methods?
โ– Use pure virtual when you want to provide an interface
to the derived types
โ– Use virtual functions when you want to provide an
interface to its derived types with default behaviour
โ– Use non-virtual functions when you want to provide
the interface to its derived types with ๏ฌxed behaviour
Templates vs. inheritance
โ– Does the type of the object affect the behaviour of the
functions in the class?
โ– If the answer is YES, then use Inheritance to model
โ– If the answer is NO, then use Generics/templates to
model
Object Oriented Design
- Best Practices
โ€“ Peter Wegner (https://en.wikipedia.org/wiki/Peter_Wegner)
โ€œObject Oriented = Objects + Classes + Inheritance!โ€
Design Practices: Even in C!
Consider	the	following	methods	from	the	C	library:	
void bcopy(const void *src, void *dst, size_t n);
void *memcpy(void *dst, const void *src, size_t n);
What	is	the	problem	in	the	interfaces	of	these	methods?	Does	it	follow	the	principles	of	good	API	design?
Design Practices: Even in C!
realloc	-	โ€œdoes	too	many	things!โ€	
#include <cstdlib>
using namespace std;
// demonstrates how malloc acts as a "complete memory manager!"
int main()
{
int* ip = (int*) realloc(NULL, sizeof(int) * 100);
// allocate 100 4-byte ints - equivalent to malloc(sizeof(int) * 100)
ip = (int*) realloc(ip, sizeof(int) * 200); // expand the memory area twice
ip = (int*) realloc(ip, sizeof(int) * 50); // shrink to half the memory area
ip = (int*) realloc(ip, 0); // equivalent to free(ip)
}
Design Practices: Even in C!
strtok	-	โ€œstateful	methods!โ€	(not	reentrant)
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Mon Jul 17 17:56:41 IST 2017";
char *token = strtok(str, ". -,;:");
do {
printf("%s n", token);
}
while(token = strtok(0, ". -,;:"));
}
Intuitive class design?
class	MyContainer {
private:	
int m_size;
public:	
void	setLength(int size)	{	m_size=	size;	}
void	setSize(int size)	{	m_size=	size;	}
int getLength()	{	return	m_size;	}
int getSize()	{	return	m_size;	}	
//	other	members	
}
Intuitive class design?
MyContainer * container = new Container;
container.setSize(0);
container.setLength(20);
cout << โ€œContainer's size is โ€ << container.getSize() <<endl;
cout << โ€œIts length is โ€œ container.getLength() <<endl;
// output:
// Container's size is 20
// Its length is 20
Calling virtual methods from a ctor
struct base {
base() {
vfun();
}
virtual void vfun() {
cout << โ€œInside base::vfunnโ€;
}
};
struct deri : base {
virtual void vfun() {
cout << โ€œInside deri::vfunnโ€;
}
};
int main(){
deri d;
}
// prints:
// Inside base::vfun
Calling virtual methods from a ctor
struct base {
base() {
base * bptr = this;
bptr->bar();
}
virtual void bar() =0;
};
struct deri: base {
void bar(){ }
};
int main() {
deri d;
}
// g++ output:
// pure virtual method called
// ABORT instruction (core dumped)
Does it happen in real-world?
โ€ข Supporting multimedia
software for my Blackberry
crashed with this design error!
โ€ข Classic OO design problem of
โ€œpolymorphic call in
constructorsโ€
โ€ข Constructors do not support fully
as the derived objects are not
constructed yet when base class
constructor executes
Best Practice
โ€œAvoid calling virtual functions from constructorsโ€
Temporary objects & NRV
class String {
public:
String(const char *str) : cstr(str) {}
String(const String& arg) {
std::cout<< โ€œString cctor nโ€;
this->cstr = arg.cstr;
}
private:
const char * cstr;
}
String function(){
return String("Hello");
}
int main(){
String s = function();
}
// without NRV optimization on, this prints:
// String cctor
// with NRV optimization on, this prints:
// String cctor
// String cctor
Intuitive overloading?
Colour (int red, int green, int blue);
Colour (float hue, float saturation, float brightness);
Intuitive overloading?
static Colour* createRGBColour(int red, int blue, int green);
static Colour* createHSBColour(float hue, float saturation, float brightness);
Intuitive overloading?
void log(double val) {
// prints the natural logarithm value of val
}
void log(String str) {
// logs the string str into the log file
}
Intuitive overloading?
void log(double val) {
// prints the natural logarithm value of val
}
void log(String str) {
// logs the string str into the log file
}
void logarithm(double val);
void logger(String str);
// or
void log(double val);
void logger(String str);
Best Practice
โ€œAvoid confusing overloadsโ€
Preventing inheritance
// C++ Example
class NoInherit {
private:
NoInherit() {
// code for constructor
}
public:
static NoInherit* createInstance() {
return new NoInherit();
}
};
// Creation of the object
NoInherit* nip = NoInherit::createInstance();
Beware of versioning problems
class Base { // provided by a third party tool
public:
virtual void vfoo(){ // introduced in version 2.0
cout<< โ€vfoo in Base โ€“ introduced in a new versionโ€;
}
// other members
};
class Derived : public Base { // some client code
public:
void vfoo(){ // was available in version 1.0
cout<< โ€vfoo in Deri โ€“ now becomes overriddenโ€;
}
// other members
};
Follow โ€œsafeโ€ overriding
#include <iostream>
#include <memory>
using namespace std;
class Base {
public:
virtual void call(int val = 10) {
cout << "The default value is: " << val << endl;
}
};
class Derived : public Base {
public:
virtual void call(int val = 20) {
cout << "The default value is: " << val << endl;
}
};
int main() {
unique_ptr<Base> b = make_unique<Derived>();
b->call();
}
// prints
// The default value is: 10
Follow โ€œsafeโ€ overriding
#include <iostream>
#include <memory>
using namespace std;
class Base {
public:
void call() {
cout << "In Base::call" << endl;
}
};
class Derived : public Base {
public:
virtual void call() {
cout << "In Derived::call" << endl;
}
};
int main() {
unique_ptr<Base> b = make_unique<Derived>();
b->call();
}
// prints
// In Base::call
Follow โ€œsafeโ€ overriding
#include <iostream>
#include <memory>
using namespace std;
class Base {
public:
virtual void call() {
cout << "in Base::call" << endl;
}
};
class Derived : public Base {
public:
virtual void call() const {
cout << "in Derived::call" << endl;
}
};
int main() {
unique_ptr<Base> b = make_unique<Derived>();
b->call();
}
// prints
// In Base::call
Best Practice
โ€œUse โ€˜overrideโ€™ keyword for safe overridingโ€
Overloading and overriding
#include <iostream>
#include <memory>
using namespace std;
class Base {
public:
virtual void call(char ch) {
cout << "In Base::call(char)" << endl;
}
virtual void call(int i) {
cout << "In Base::call(int)" << endl;
}
};
class Derived : public Base {
public:
virtual void call(char ch) {
cout << "In Derived::call(char)" << endl;
}
};
int main() {
unique_ptr<Base> b = make_unique<Derived>();
b->call(10);
}
Selectively introduce types
// in mymath.h
namespace math {
class scalar { /* โ€ฆ */ }
class vector { /* โ€ฆ */ }
// other members
}
// in use.cpp
// for using std::vector:
#include <vector>
using namespace std;
// for using the scalar class in your math namespace:
#include โ€œmymath.hโ€
using namespace math;
int main() {
vector<scalar *> v;
// compiler error: vector is ambiguous
// does vector refer to std::vector or math::vector?
}
Selectively expose types to clients
namespace {
int someMem;
void somefunction();
};
// is a better way to limit names to file scope
// than the following:
static int someMem;
static void somefunction();
Hiding?
int x, y; // global variables x and y
class Point {
public:
int x, y; // class members x and y
Point(int x, int y); // function arguments x and y
};
// Point constructor for setting values of x and y data members
// C++
Point::Point(int x, int y) {
x = x;
y = y;
}
Beware of hiding
void foo { // outer block
int x, y;
{ // inner block
int x = 10, y = 20;
// hides the outer x and y
}
}
Long parameter lists
Are arrays polymorphic?
class base {
int basemem;
public:
base() : basemem(10) {}
int getint() {
return basemem;
}
// other members
};
class derived : public base {
๏ฌ‚oat derivedmem;
public:
derived() : base(), derivedmem(20.0f) {}
// other members
};
void print(base *bPtr, int size) {
for(int i = 0; i < size; i++, bPtr++)
cout<< bPtr->getint() << endl;
}
int main() {
base b[5];
// prints ๏ฌve 10's correctly
print(b, 5);
derived d[5];
// does not print ๏ฌve 10's correctly
print(d, 5);
}
Books to read
Effective Object Oriented Design in Cpp
Effective Object Oriented Design in Cpp
Effective Object Oriented Design in Cpp
Effective Object Oriented Design in Cpp
Effective Object Oriented Design in Cpp
โ€œApplying design principles is the key to creating
high-quality software!โ€
Architectural principles:
Axis, symmetry, rhythm, datum, hierarchy, transformation
Effective Object Oriented Design in Cpp
Image/video credits
โ– http://en.wikipedia.org/wiki/Fear_of_missing_out
โ– http://lesliejanemoran.blogspot.in/2010_05_01_archive.html
โ– http://javra.eu/wp-content/uploads/2013/07/angry_laptop2.jpg
โ– https://www.youtube.com/watch?v=5R8XHrfJkeg
โ– http://womenworld.org/image/052013/31/113745161.jpg
โ– http://www.fantom-xp.com/wallpapers/33/I'm_not_sure.jpg
โ– https://www.๏ฌ‚ickr.com/photos/31457017@N00/453784086
โ– https://www.gradtouch.com/uploads/images/question3.jpg
โ– http://gurujohn.๏ฌles.wordpress.com/2008/06/bookcover0001.jpg
โ– http://upload.wikimedia.org/wikipedia/commons/d/d5/Martin_Fowler_-_Swipe_Conference_2012.jpg
โ– http://www.codeproject.com/KB/architecture/csdespat_2/dpcs_br.gif
โ– http://upload.wikimedia.org/wikipedia/commons/thumb/2/28/Bertrand_Meyer_IMG_2481.jpg/440px-
Bertrand_Meyer_IMG_2481.jpg
โ– http://takeji-soft.up.n.seesaa.net/takeji-soft/image/GOF-OOPLSA-94-Color-75.jpg?d=a0
โ– https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/OOP_ObjC/Art/watchcalls_35.gif
โ– http://www.pluspack.com/๏ฌles/billeder/Newsletter/25/takeaway_bag.png
โ– http://cdn1.tnwcdn.com/wp-content/blogs.dir/1/๏ฌles/2013/03/design.jpg
โ– http://img01.deviantart.net/d8ab/i/2016/092/c/2/may_the_force_be_with_you___yoda_๏ฌ‚ag_by_os๏ฌ‚ag-d9xe904.jpg
ganesh@codeops.tech @GSamarthyam
www.codeops.tech slideshare.net/sgganesh
+91 98801 64463 bit.ly/sgganesh

More Related Content

What's hot (20)

PPTX
Summary of C++17 features
Bartlomiej Filipek
ย 
PDF
Building DSLs with Xtext - Eclipse Modeling Day 2009
Heiko Behrens
ย 
PDF
Modern C++ Explained: Move Semantics (Feb 2018)
Olve Maudal
ย 
PPT
Project Lambda - Closures after all?
Andreas Enbohm
ย 
PPTX
FParsec Hands On - F#unctional Londoners 2014
Phillip Trelford
ย 
PDF
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Tudor Dragan
ย 
PDF
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
ย 
PPTX
Code is not text! How graph technologies can help us to understand our code b...
Andreas Dewes
ย 
PPTX
The Style of C++ 11
Sasha Goldshtein
ย 
PDF
Xtext Webinar
Heiko Behrens
ย 
PDF
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Francesco Casalegno
ย 
PPTX
Learning from other's mistakes: Data-driven code analysis
Andreas Dewes
ย 
PPTX
C++11: Feel the New Language
mspline
ย 
PDF
C++11 & C++14
CyberPlusIndia
ย 
PDF
CS4200 2019 | Lecture 3 | Parsing
Eelco Visser
ย 
PPTX
Kotlin as a Better Java
Garth Gilmour
ย 
PDF
Modern C++
Michael Clark
ย 
PDF
Writing Parsers and Compilers with PLY
David Beazley (Dabeaz LLC)
ย 
PDF
The Rust Programming Language: an Overview
Roberto Casadei
ย 
Summary of C++17 features
Bartlomiej Filipek
ย 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Heiko Behrens
ย 
Modern C++ Explained: Move Semantics (Feb 2018)
Olve Maudal
ย 
Project Lambda - Closures after all?
Andreas Enbohm
ย 
FParsec Hands On - F#unctional Londoners 2014
Phillip Trelford
ย 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Tudor Dragan
ย 
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
ย 
Code is not text! How graph technologies can help us to understand our code b...
Andreas Dewes
ย 
The Style of C++ 11
Sasha Goldshtein
ย 
Xtext Webinar
Heiko Behrens
ย 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Francesco Casalegno
ย 
Learning from other's mistakes: Data-driven code analysis
Andreas Dewes
ย 
C++11: Feel the New Language
mspline
ย 
C++11 & C++14
CyberPlusIndia
ย 
CS4200 2019 | Lecture 3 | Parsing
Eelco Visser
ย 
Kotlin as a Better Java
Garth Gilmour
ย 
Modern C++
Michael Clark
ย 
Writing Parsers and Compilers with PLY
David Beazley (Dabeaz LLC)
ย 
The Rust Programming Language: an Overview
Roberto Casadei
ย 

Similar to Effective Object Oriented Design in Cpp (20)

PDF
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
ย 
PDF
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
ย 
PPTX
.NET Foundation, Future of .NET and C#
Bertrand Le Roy
ย 
PDF
ะ”ะผะธั‚ั€ะธะน ะ’ะตั€ะตัะบัƒะฝ ยซะกะธะฝั‚ะฐะบัะธั‡ะตัะบะธะน ัะฐั…ะฐั€ C#ยป
SpbDotNet Community
ย 
PPT
An Overview Of Python With Functional Programming
Adam Getchell
ย 
PPT
Cpp tutorial
Vikas Sharma
ย 
PPTX
Novidades do c# 7 e 8
Giovanni Bassi
ย 
PPT
CIntro_Up_To_Functions.ppt;uoooooooooooooooooooo
muhammedcti23240202
ย 
PPT
C#
Joni
ย 
PDF
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
tdc-globalcode
ย 
PPT
C Tutorials
Sudharsan S
ย 
PDF
Kotlin, smarter development for the jvm
Arnaud Giuliani
ย 
PDF
Python basic
Saifuddin Kaijar
ย 
PPT
CppTutorial.ppt
HODZoology3
ย 
PPTX
PRINCE PRESENTATION(1).pptx
SajalKesharwani2
ย 
PDF
Clean Code at Silicon Valley Code Camp 2011 (02/17/2012)
Theo Jungeblut
ย 
PDF
Compiler Case Study - Design Patterns in C#
CodeOps Technologies LLP
ย 
PPTX
C# Today and Tomorrow
Bertrand Le Roy
ย 
PDF
C# 7.x What's new and what's coming with C# 8
Christian Nagel
ย 
PPTX
Introduction Of C++
Sangharsh agarwal
ย 
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
ย 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
ย 
.NET Foundation, Future of .NET and C#
Bertrand Le Roy
ย 
ะ”ะผะธั‚ั€ะธะน ะ’ะตั€ะตัะบัƒะฝ ยซะกะธะฝั‚ะฐะบัะธั‡ะตัะบะธะน ัะฐั…ะฐั€ C#ยป
SpbDotNet Community
ย 
An Overview Of Python With Functional Programming
Adam Getchell
ย 
Cpp tutorial
Vikas Sharma
ย 
Novidades do c# 7 e 8
Giovanni Bassi
ย 
CIntro_Up_To_Functions.ppt;uoooooooooooooooooooo
muhammedcti23240202
ย 
C#
Joni
ย 
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
tdc-globalcode
ย 
C Tutorials
Sudharsan S
ย 
Kotlin, smarter development for the jvm
Arnaud Giuliani
ย 
Python basic
Saifuddin Kaijar
ย 
CppTutorial.ppt
HODZoology3
ย 
PRINCE PRESENTATION(1).pptx
SajalKesharwani2
ย 
Clean Code at Silicon Valley Code Camp 2011 (02/17/2012)
Theo Jungeblut
ย 
Compiler Case Study - Design Patterns in C#
CodeOps Technologies LLP
ย 
C# Today and Tomorrow
Bertrand Le Roy
ย 
C# 7.x What's new and what's coming with C# 8
Christian Nagel
ย 
Introduction Of C++
Sangharsh agarwal
ย 
Ad

More from CodeOps Technologies LLP (20)

PDF
AWS Serverless Event-driven Architecture - in lastminute.com meetup
CodeOps Technologies LLP
ย 
PPTX
Understanding azure batch service
CodeOps Technologies LLP
ย 
PDF
DEVOPS AND MACHINE LEARNING
CodeOps Technologies LLP
ย 
PDF
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONS
CodeOps Technologies LLP
ย 
PPT
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
CodeOps Technologies LLP
ย 
PPTX
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
CodeOps Technologies LLP
ย 
PPTX
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
CodeOps Technologies LLP
ย 
PPTX
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
CodeOps Technologies LLP
ย 
PPTX
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CodeOps Technologies LLP
ย 
PPTX
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
CodeOps Technologies LLP
ย 
PPTX
Training And Serving ML Model Using Kubeflow by Jayesh Sharma
CodeOps Technologies LLP
ย 
PPTX
Deploy Microservices To Kubernetes Without Secrets by Reenu Saluja
CodeOps Technologies LLP
ย 
PDF
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
CodeOps Technologies LLP
ย 
PDF
YAML Tips For Kubernetes by Neependra Khare
CodeOps Technologies LLP
ย 
PDF
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
CodeOps Technologies LLP
ย 
PPTX
Monitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
CodeOps Technologies LLP
ย 
PDF
Jet brains space intro presentation
CodeOps Technologies LLP
ย 
PDF
Functional Programming in Java 8 - Lambdas and Streams
CodeOps Technologies LLP
ย 
PPTX
Distributed Tracing: New DevOps Foundation
CodeOps Technologies LLP
ย 
PDF
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
CodeOps Technologies LLP
ย 
AWS Serverless Event-driven Architecture - in lastminute.com meetup
CodeOps Technologies LLP
ย 
Understanding azure batch service
CodeOps Technologies LLP
ย 
DEVOPS AND MACHINE LEARNING
CodeOps Technologies LLP
ย 
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONS
CodeOps Technologies LLP
ย 
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
CodeOps Technologies LLP
ย 
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
CodeOps Technologies LLP
ย 
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
CodeOps Technologies LLP
ย 
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
CodeOps Technologies LLP
ย 
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CodeOps Technologies LLP
ย 
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
CodeOps Technologies LLP
ย 
Training And Serving ML Model Using Kubeflow by Jayesh Sharma
CodeOps Technologies LLP
ย 
Deploy Microservices To Kubernetes Without Secrets by Reenu Saluja
CodeOps Technologies LLP
ย 
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
CodeOps Technologies LLP
ย 
YAML Tips For Kubernetes by Neependra Khare
CodeOps Technologies LLP
ย 
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
CodeOps Technologies LLP
ย 
Monitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
CodeOps Technologies LLP
ย 
Jet brains space intro presentation
CodeOps Technologies LLP
ย 
Functional Programming in Java 8 - Lambdas and Streams
CodeOps Technologies LLP
ย 
Distributed Tracing: New DevOps Foundation
CodeOps Technologies LLP
ย 
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
CodeOps Technologies LLP
ย 
Ad

Recently uploaded (20)

PDF
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
ย 
PDF
AWS Consulting Services: Empowering Digital Transformation with Nlineaxis
Nlineaxis IT Solutions Pvt Ltd
ย 
PPTX
declaration of Variables and constants.pptx
meemee7378
ย 
PPTX
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
ย 
PDF
OpenChain Webinar - AboutCode - Practical Compliance in One Stack โ€“ Licensing...
Shane Coughlan
ย 
PDF
Automated Test Case Repair Using Language Models
Lionel Briand
ย 
PPTX
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
ย 
PPTX
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
ย 
PDF
Building scalbale cloud native apps with .NET 8
GillesMathieu10
ย 
PPTX
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
ย 
PDF
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
ย 
PPTX
Agentforce โ€“ TDX 2025 Hackathon Achievement
GetOnCRM Solutions
ย 
PPTX
arctitecture application system design os dsa
za241967
ย 
DOCX
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
ย 
PDF
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
ย 
PPTX
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
ย 
PDF
What Is an Internal Quality Audit and Why It Matters for Your QMS
BizPortals365
ย 
PDF
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
ย 
PDF
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
ย 
PDF
AI Software Development Process, Strategies and Challenges
Net-Craft.com
ย 
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
ย 
AWS Consulting Services: Empowering Digital Transformation with Nlineaxis
Nlineaxis IT Solutions Pvt Ltd
ย 
declaration of Variables and constants.pptx
meemee7378
ย 
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
ย 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack โ€“ Licensing...
Shane Coughlan
ย 
Automated Test Case Repair Using Language Models
Lionel Briand
ย 
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
ย 
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
ย 
Building scalbale cloud native apps with .NET 8
GillesMathieu10
ย 
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
ย 
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
ย 
Agentforce โ€“ TDX 2025 Hackathon Achievement
GetOnCRM Solutions
ย 
arctitecture application system design os dsa
za241967
ย 
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
ย 
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
ย 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
ย 
What Is an Internal Quality Audit and Why It Matters for Your QMS
BizPortals365
ย 
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
ย 
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
ย 
AI Software Development Process, Strategies and Challenges
Net-Craft.com
ย 

Effective Object Oriented Design in Cpp

  • 1. OOP in C++ Ganesh Samarthyam [email protected]
  • 2. โ€œThere are two ways of constructing a software design: One way is to make it so simple that there are obviously no de๏ฌciencies, and the other way is to make it so complicated that there are no obvious de๏ฌciencies. The ๏ฌrst method is far more dif๏ฌcult.โ€ C. A. R. Hoare
  • 3. Example of beautiful design int arr[] = {1, 4, 9, 16, 25}; // some values // find the first occurrence of 9 in the array int * arr_pos = find(arr, arr + 4, 9); std::cout<< โ€œarray pos = โ€œ<< arr_pos - arr << endl; vector<int> int_vec; for(int i = 1; i <= 5; i++) int_vec.push_back(i*i); vector<int>::iterator vec_pos = find (int_vec.begin(), int_vec.end(), 9); std::cout<< โ€œvector pos = โ€œ<< (vec_pos - int_vec.begin());
  • 4. "The critical design tool for software development is a mind well educated in design principles" - Craig Larman
  • 5. Robert C. Martin Formulated many principles and described many other important principles
  • 6. Michael Feathers Michael Feathers coined the acronym SOLID in 2000s to remember ๏ฌrst ๏ฌve of the numerous principles by Robert C. Martin
  • 7. SOLID principles S Single Responsibility Principle Every object should have a single responsibility and that should be encapsulated by the class O Open Closed Principle Software should be open for extension, but closed for modification L Liskovโ€™s Substitution Principle Any subclass should always be usable instead of its parent class I Interface Segregation Principle Many client specific interfaces are better than one general purpose interface D Dependency Inversion Principle Abstractions should not depend upon details. Details should depend upon abstractions
  • 8. 3 principles behind patterns Design'principles' behind'pa0erns' Program'to'an' interface,'not'to'an' implementa7on'' Favor'object' composi7on'' over'inheritance' Encapsulate'what' varies'
  • 10. How to apply principles in practice? Design principles Code How to bridge the gap?
  • 11. Why care about refactoring? As an evolving program is continually changed, its complexity, reflecting deteriorating structure, increases unless work is done to maintain or reduce it - Lehman's law of Increasing Complexity
  • 12. What is refactoring? Refactoring (noun): a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior Refactor (verb): to restructure software by applying a series of refactorings without changing its observable behavior
  • 15. Procedural code #include <string> #include <iostream> using namespace std; enum Animal { rat, pig, frog }; string talk(enum Animal animal) { switch(animal) { case rat: return "squeak"; case pig: return "oink"; case frog: return "ribbit"; default: return "unrecognized case value"; } } int main() { enum Animal animal = pig; cout << talk(animal) << endl; }
  • 16. Object oriented code #include <string> #include <iostream> using namespace std; class Animal { public: virtual string talk() = 0; }; class Rat : public Animal { public: string talk() override { return "squeak"; } }; class Pig : public Animal { public: string talk() override { return "oink"; } }; class Frog : public Animal { public: string talk() override { return "ribbit"; } }; int main() { Pig pig; Animal &animal = pig; cout << animal.talk() << endl; }
  • 17. Functional code #include <iostream> using namespace std; int main() { auto rat = []() { return "squeak"; }; auto pig = []() { return "oink"; }; auto frog = []() { return "ribbit"; }; auto animaltalk = pig; cout << animaltalk() << endl; }
  • 18. Generic code #include <string> #include <iostream> using namespace std; enum Animal { rat, pig, frog }; typedef const char * cstring; template <enum Animal animal> struct talk { static constexpr cstring value = "undefined"; }; template <> struct talk<rat> { static constexpr cstring value = "squeak"; }; template <> struct talk<pig> { static constexpr cstring value = "oink"; }; template <> struct talk<frog> { static constexpr cstring value = "ribbit"; }; int main() { cout << talk<pig>::value << endl; }
  • 20. Inheritance vs. composition โ– A common base class means common behaviour to its derived types โ– Public inheritance means โ€œis-aโ€ relationship โ– Private inheritance means โ€œis-implemented-in-terms-ofโ€ โ– Composition means โ€œhas-aโ€ or โ€œis-implemented-in- terms-ofโ€
  • 21. Virtual or non-virtual methods? โ– Use pure virtual when you want to provide an interface to the derived types โ– Use virtual functions when you want to provide an interface to its derived types with default behaviour โ– Use non-virtual functions when you want to provide the interface to its derived types with ๏ฌxed behaviour
  • 22. Templates vs. inheritance โ– Does the type of the object affect the behaviour of the functions in the class? โ– If the answer is YES, then use Inheritance to model โ– If the answer is NO, then use Generics/templates to model
  • 23. Object Oriented Design - Best Practices
  • 24. โ€“ Peter Wegner (https://en.wikipedia.org/wiki/Peter_Wegner) โ€œObject Oriented = Objects + Classes + Inheritance!โ€
  • 25. Design Practices: Even in C! Consider the following methods from the C library: void bcopy(const void *src, void *dst, size_t n); void *memcpy(void *dst, const void *src, size_t n); What is the problem in the interfaces of these methods? Does it follow the principles of good API design?
  • 26. Design Practices: Even in C! realloc - โ€œdoes too many things!โ€ #include <cstdlib> using namespace std; // demonstrates how malloc acts as a "complete memory manager!" int main() { int* ip = (int*) realloc(NULL, sizeof(int) * 100); // allocate 100 4-byte ints - equivalent to malloc(sizeof(int) * 100) ip = (int*) realloc(ip, sizeof(int) * 200); // expand the memory area twice ip = (int*) realloc(ip, sizeof(int) * 50); // shrink to half the memory area ip = (int*) realloc(ip, 0); // equivalent to free(ip) }
  • 27. Design Practices: Even in C! strtok - โ€œstateful methods!โ€ (not reentrant) #include <stdio.h> #include <string.h> int main() { char str[] = "Mon Jul 17 17:56:41 IST 2017"; char *token = strtok(str, ". -,;:"); do { printf("%s n", token); } while(token = strtok(0, ". -,;:")); }
  • 28. Intuitive class design? class MyContainer { private: int m_size; public: void setLength(int size) { m_size= size; } void setSize(int size) { m_size= size; } int getLength() { return m_size; } int getSize() { return m_size; } // other members }
  • 29. Intuitive class design? MyContainer * container = new Container; container.setSize(0); container.setLength(20); cout << โ€œContainer's size is โ€ << container.getSize() <<endl; cout << โ€œIts length is โ€œ container.getLength() <<endl; // output: // Container's size is 20 // Its length is 20
  • 30. Calling virtual methods from a ctor struct base { base() { vfun(); } virtual void vfun() { cout << โ€œInside base::vfunnโ€; } }; struct deri : base { virtual void vfun() { cout << โ€œInside deri::vfunnโ€; } }; int main(){ deri d; } // prints: // Inside base::vfun
  • 31. Calling virtual methods from a ctor struct base { base() { base * bptr = this; bptr->bar(); } virtual void bar() =0; }; struct deri: base { void bar(){ } }; int main() { deri d; } // g++ output: // pure virtual method called // ABORT instruction (core dumped)
  • 32. Does it happen in real-world? โ€ข Supporting multimedia software for my Blackberry crashed with this design error! โ€ข Classic OO design problem of โ€œpolymorphic call in constructorsโ€ โ€ข Constructors do not support fully as the derived objects are not constructed yet when base class constructor executes
  • 33. Best Practice โ€œAvoid calling virtual functions from constructorsโ€
  • 34. Temporary objects & NRV class String { public: String(const char *str) : cstr(str) {} String(const String& arg) { std::cout<< โ€œString cctor nโ€; this->cstr = arg.cstr; } private: const char * cstr; } String function(){ return String("Hello"); } int main(){ String s = function(); } // without NRV optimization on, this prints: // String cctor // with NRV optimization on, this prints: // String cctor // String cctor
  • 35. Intuitive overloading? Colour (int red, int green, int blue); Colour (float hue, float saturation, float brightness);
  • 36. Intuitive overloading? static Colour* createRGBColour(int red, int blue, int green); static Colour* createHSBColour(float hue, float saturation, float brightness);
  • 37. Intuitive overloading? void log(double val) { // prints the natural logarithm value of val } void log(String str) { // logs the string str into the log file }
  • 38. Intuitive overloading? void log(double val) { // prints the natural logarithm value of val } void log(String str) { // logs the string str into the log file } void logarithm(double val); void logger(String str); // or void log(double val); void logger(String str);
  • 40. Preventing inheritance // C++ Example class NoInherit { private: NoInherit() { // code for constructor } public: static NoInherit* createInstance() { return new NoInherit(); } }; // Creation of the object NoInherit* nip = NoInherit::createInstance();
  • 41. Beware of versioning problems class Base { // provided by a third party tool public: virtual void vfoo(){ // introduced in version 2.0 cout<< โ€vfoo in Base โ€“ introduced in a new versionโ€; } // other members }; class Derived : public Base { // some client code public: void vfoo(){ // was available in version 1.0 cout<< โ€vfoo in Deri โ€“ now becomes overriddenโ€; } // other members };
  • 42. Follow โ€œsafeโ€ overriding #include <iostream> #include <memory> using namespace std; class Base { public: virtual void call(int val = 10) { cout << "The default value is: " << val << endl; } }; class Derived : public Base { public: virtual void call(int val = 20) { cout << "The default value is: " << val << endl; } }; int main() { unique_ptr<Base> b = make_unique<Derived>(); b->call(); } // prints // The default value is: 10
  • 43. Follow โ€œsafeโ€ overriding #include <iostream> #include <memory> using namespace std; class Base { public: void call() { cout << "In Base::call" << endl; } }; class Derived : public Base { public: virtual void call() { cout << "In Derived::call" << endl; } }; int main() { unique_ptr<Base> b = make_unique<Derived>(); b->call(); } // prints // In Base::call
  • 44. Follow โ€œsafeโ€ overriding #include <iostream> #include <memory> using namespace std; class Base { public: virtual void call() { cout << "in Base::call" << endl; } }; class Derived : public Base { public: virtual void call() const { cout << "in Derived::call" << endl; } }; int main() { unique_ptr<Base> b = make_unique<Derived>(); b->call(); } // prints // In Base::call
  • 45. Best Practice โ€œUse โ€˜overrideโ€™ keyword for safe overridingโ€
  • 46. Overloading and overriding #include <iostream> #include <memory> using namespace std; class Base { public: virtual void call(char ch) { cout << "In Base::call(char)" << endl; } virtual void call(int i) { cout << "In Base::call(int)" << endl; } }; class Derived : public Base { public: virtual void call(char ch) { cout << "In Derived::call(char)" << endl; } }; int main() { unique_ptr<Base> b = make_unique<Derived>(); b->call(10); }
  • 47. Selectively introduce types // in mymath.h namespace math { class scalar { /* โ€ฆ */ } class vector { /* โ€ฆ */ } // other members } // in use.cpp // for using std::vector: #include <vector> using namespace std; // for using the scalar class in your math namespace: #include โ€œmymath.hโ€ using namespace math; int main() { vector<scalar *> v; // compiler error: vector is ambiguous // does vector refer to std::vector or math::vector? }
  • 48. Selectively expose types to clients namespace { int someMem; void somefunction(); }; // is a better way to limit names to file scope // than the following: static int someMem; static void somefunction();
  • 49. Hiding? int x, y; // global variables x and y class Point { public: int x, y; // class members x and y Point(int x, int y); // function arguments x and y }; // Point constructor for setting values of x and y data members // C++ Point::Point(int x, int y) { x = x; y = y; }
  • 50. Beware of hiding void foo { // outer block int x, y; { // inner block int x = 10, y = 20; // hides the outer x and y } }
  • 52. Are arrays polymorphic? class base { int basemem; public: base() : basemem(10) {} int getint() { return basemem; } // other members }; class derived : public base { ๏ฌ‚oat derivedmem; public: derived() : base(), derivedmem(20.0f) {} // other members }; void print(base *bPtr, int size) { for(int i = 0; i < size; i++, bPtr++) cout<< bPtr->getint() << endl; } int main() { base b[5]; // prints ๏ฌve 10's correctly print(b, 5); derived d[5]; // does not print ๏ฌve 10's correctly print(d, 5); }
  • 59. โ€œApplying design principles is the key to creating high-quality software!โ€ Architectural principles: Axis, symmetry, rhythm, datum, hierarchy, transformation
  • 61. Image/video credits โ– http://en.wikipedia.org/wiki/Fear_of_missing_out โ– http://lesliejanemoran.blogspot.in/2010_05_01_archive.html โ– http://javra.eu/wp-content/uploads/2013/07/angry_laptop2.jpg โ– https://www.youtube.com/watch?v=5R8XHrfJkeg โ– http://womenworld.org/image/052013/31/113745161.jpg โ– http://www.fantom-xp.com/wallpapers/33/I'm_not_sure.jpg โ– https://www.๏ฌ‚ickr.com/photos/31457017@N00/453784086 โ– https://www.gradtouch.com/uploads/images/question3.jpg โ– http://gurujohn.๏ฌles.wordpress.com/2008/06/bookcover0001.jpg โ– http://upload.wikimedia.org/wikipedia/commons/d/d5/Martin_Fowler_-_Swipe_Conference_2012.jpg โ– http://www.codeproject.com/KB/architecture/csdespat_2/dpcs_br.gif โ– http://upload.wikimedia.org/wikipedia/commons/thumb/2/28/Bertrand_Meyer_IMG_2481.jpg/440px- Bertrand_Meyer_IMG_2481.jpg โ– http://takeji-soft.up.n.seesaa.net/takeji-soft/image/GOF-OOPLSA-94-Color-75.jpg?d=a0 โ– https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/OOP_ObjC/Art/watchcalls_35.gif โ– http://www.pluspack.com/๏ฌles/billeder/Newsletter/25/takeaway_bag.png โ– http://cdn1.tnwcdn.com/wp-content/blogs.dir/1/๏ฌles/2013/03/design.jpg โ– http://img01.deviantart.net/d8ab/i/2016/092/c/2/may_the_force_be_with_you___yoda_๏ฌ‚ag_by_os๏ฌ‚ag-d9xe904.jpg