c++ & design patterns - primera parte

28
C++ CONCEPTS & DEFINITIONS A program that is planned before coding will become a working program before an unplanned program. 1 Good Sources...............................................................................4 1.1 C++ FAQLite Marshall Cline.............................................................4 1.2 C++ FQA Yossi Kreinin..................................................................4 2 CLASS......................................................................................4 3 OBJECT.....................................................................................5 4 ABSTRACTION:...............................................................................5 5 ENCAPSULATION..............................................................................5 6 OVERLOADING................................................................................5 Operator Overloading, Function Overloading....................................................5 Overloading new & delete......................................................................5 7 GENERICITY.................................................................................5 8 INHERITANCE & DATA ENCAPSULATION...........................................................5 9 POLYMORPHISM: (types)......................................................................6 10 TEMPLATE.................................................................................6 11 DYNAMIC BINDING / VIRTUAL FUNCTION.......................................................6 12 ABSTRACT BASE CLASS......................................................................7 13 NAMESPACE................................................................................7 14 EXCEPTION HANDLING: (types – by value, reference, type)..................................7 15 CONTAINERS...............................................................................7 16 STANDARD TEMPLATE LIBRARY................................................................7 17 A FUNCTION OBJECT (FUNCTOR)..............................................................8 18 C – C++ MAIN DIFFERENCES.................................................................9 19 REFERENCE................................................................................9 20 MUTABLE..................................................................................9 21 INITIALIZATION LIST......................................................................9 22 C++ CASTS...............................................................................10 23 CPPUNIT.................................................................................10 24 DESIGN PATTERNS.........................................................................11 24.1 Creational Patterns...................................................................16 24.2 Structural Patterns...................................................................17 24.4 Behavioral Patterns...................................................................18 24.5 Concurrency Patterns..................................................................19 25 EXPLICITLY DISALLOW USE OF COMPILER GENERATED FUNCTIONS.................................19 26 C++ & JAVA QUICK COMPARISON.............................................................20 Page | 1

Upload: nikunj-parekh

Post on 12-Apr-2017

237 views

Category:

Software


3 download

TRANSCRIPT

Page 1: C++ & Design Patterns - primera parte

C++ CONCEPTS & DEFINITIONS

A program that is planned before coding will become a working program before an unplanned program.1 Good Sources......................................................................................................................................................................................................4

1.1 C++ FAQLite Marshall Cline.....................................................................................................................................................................4

1.2 C++ FQA Yossi Kreinin..............................................................................................................................................................................4

2 CLASS..................................................................................................................................................................................................................4

3 OBJECT................................................................................................................................................................................................................5

4 ABSTRACTION:....................................................................................................................................................................................................5

5 ENCAPSULATION.................................................................................................................................................................................................5

6 OVERLOADING....................................................................................................................................................................................................5

Operator Overloading, Function Overloading.........................................................................................................................................................5

Overloading new & delete.......................................................................................................................................................................................5

7 GENERICITY.........................................................................................................................................................................................................5

8 INHERITANCE & DATA ENCAPSULATION............................................................................................................................................................5

9 POLYMORPHISM: (types)....................................................................................................................................................................................6

10 TEMPLATE.....................................................................................................................................................................................................6

11 DYNAMIC BINDING / VIRTUAL FUNCTION....................................................................................................................................................6

12 ABSTRACT BASE CLASS..................................................................................................................................................................................7

13 NAMESPACE..................................................................................................................................................................................................7

14 EXCEPTION HANDLING: (types – by value, reference, type)........................................................................................................................7

15 CONTAINERS..................................................................................................................................................................................................7

16 STANDARD TEMPLATE LIBRARY....................................................................................................................................................................7

17 A FUNCTION OBJECT (FUNCTOR)..................................................................................................................................................................8

18 C – C++ MAIN DIFFERENCES..........................................................................................................................................................................9

19 REFERENCE....................................................................................................................................................................................................9

20 MUTABLE.......................................................................................................................................................................................................9

21 INITIALIZATION LIST......................................................................................................................................................................................9

22 C++ CASTS....................................................................................................................................................................................................10

23 CPPUNIT......................................................................................................................................................................................................10

24 DESIGN PATTERNS.......................................................................................................................................................................................11

24.1 Creational Patterns................................................................................................................................................................................16

24.2 Structural Patterns.................................................................................................................................................................................17

24.4 Behavioral Patterns...............................................................................................................................................................................18

24.5 Concurrency Patterns............................................................................................................................................................................19

25 EXPLICITLY DISALLOW USE OF COMPILER GENERATED FUNCTIONS..........................................................................................................19

26 C++ & JAVA QUICK COMPARISON...............................................................................................................................................................20

Page | 1

Page 2: C++ & Design Patterns - primera parte

Good Sources :2.1 C++ FAQLite Marshall Cline

2.2 C++ FQA Yossi Kreinin

2.3 C++11 FAQ Stroustrup

CLASS :

A class is a user defined data type. It combines representation of properties (behavior) of a “concept” with methods to work with it. In context of C++, a class also has access specifiers like public, private and protected, and default initializers like constructors and destructors. If “it” is a new “idea”/“concept”, make it a class.

OBJECT :Singh: Object is a self-contained independent entity that has properties and methods. Methods alter the value of properties. This determines behavior of the object.

An object is an instance of a class. Each object is a separate “entity” of the instantiated “concept” or the class. (If “it” is a separate entity (yours v/s mine…), make it a object of a class.)

ABSTRACTION :Carries ‘fundamental’ properties, so that it can be inherited for actual use…

ENCAPSULATION :A language feature that provides access control to members of a class – private, protected.

OVERLOADING :It is …

7.1 Operator Overloading, Function Overloading:Operator overloading allows C/C++ operators to have user-defined meanings on user-defined types (classes). Overloaded operators are syntactic sugar for function calls. At least one operator has to be a class/user defined type. ++x returns by reference and is FASTER, x++ returns by value & takes dummy int arg.

7.2 Overloading new & delete:If new is overloaded, delete should also be. Because, if overloaded new threw exception, it’d only call an overloaded delete.

GENERICITY :It is the feature of a programming language that allows data-type independent implementations. In context of C++, the keyword “template” enables type-independent programming. Using this keyword, algorithms (functions) or classes can be implemented as templates. The code is automatically generated at compile time for the specific data type, based on usage/call.

Page | 2

Page 3: C++ & Design Patterns - primera parte

INHERITANCE & DATA ENCAPSULATION :A mechanism to support distinction between the “commonality” & the “uniqueness” in properties of objects. This distinction is the “facility to allow extending properties”. Common properties belong in a “base” class & unique properties belong in a “derived” class.

In context of C++, there are 3 ways to inherit common properties; consequently there are 3 types of inheritance:

1. Behavioral Inheritance public Models IS-A relation Shares behavior

Family_Car : IS_A Car IS_A : Automobile

2. Composition (Implementation Inheritance) private & protected here = Alternative to containment

3. Aggregation/Containment : including objects as members of other objects depicts ‘containment’ or ‘composition’

4. Interface Inheritance abstract base class Base only declares methods; Derived classes implement

5. Virtual Inheritance Keeps only a single copy of base class members in the class hierarchy, in case of multiple inheritance. Keyword virtual used at first level of derived classes (sort of anticipating multi-inheritance!)

6. Architectural choices between Multiple inheritance v/s Nested Generalization v/s Bridge pattern

Due to this control of access, the first step of debugging – localization – is completed before program is even run.

POLYMORPHISM : (types)In Greek, “poly” means “many” and “morph” means taking many forms. In the context of C++, Polymorphism is the ability to implement “multiple implementations of an action” and automatically select correct implementation based on the “context”.

For example a class may provide two functions with similar implementation and same name but different parameter types. The compiler will “bind” the correct function to the call at compile time or run time (An example of compile time polymorphism is templates.)

//polymorphism facilitates an object reference to refer at compile time OR at run time to an //instance of any of the derived classes. The right derived class method gets invoked at runtime //even while using a base class pointer using “dynamic binding”.

TEMPLATE :When classes need to be created that basically have the same contents except data-type of few members, a class template can be used. Similarly function templates..

DYNAMIC BINDING / VIRTUAL FUNCTION :A virtual function allows derived classes to replace the implementation provided by the base class AT RUNTIME. This allows algorithms in base class to be replaced (partly/fully) by those in derived class, even using base class pointer, and automatically .

Page | 3

Page 4: C++ & Design Patterns - primera parte

Details: The function for which calling “interface” can be defined but “implementation” cannot be defined is “virtual function”. Using the keyword “virtual” to do this enables the so called “dynamic binding”. DYNAMIC BINDING IS IN EFFECT ONLY WHEN YOU REFER BY POINTER.

Mechanics: If the object has one or more virtual functions, the compiler puts one hidden pointer in the object called a "virtual-pointer" or "v-pointer". This v-pointer points to a global table called the "virtual-table" or "v-table" shared across all objects of the class. The compiler creates a v-table for each class with at least one virtual function. During a dispatch of a virtual function, the run-time system follows the object's v-pointer to the class's v-table, and then follows the appropriate slot in the v-table to the method code. Small space (global array of fn pointers) and small time (ptr indirection) overhead.

ABSTRACT BASE CLASS ://If 2 classes have common “interface”, make the interface the “abstract base class”.

//If 2 classes have common “implementation”, make the implementation the “base class”.

NAMESPACE :A namespace defines a “scope” in which a set of variables or functions or data-types are accessible. A namespace can be made accessible with the use of “using” directive. If a set of classes and templates are related, keep them in “same” namespace.

EXCEPTION HANDLING : (types – by value, reference, type)Language feature providing method to automatically detect & handle abnormal program situations at runtime.

API library providers know “when” an error occurs but don’t know perfect way to handle it; API clients know how to handle the error but need to know when it arises. Exception handling communicates the error situation appropriately.

CONTAINERS :A container is a class with main purpose of “holding” several objects. Example, vector, list etc.

STANDARD TEMPLATE LIBRARY : Reference Example

The C++ STL contains efficient built-in data-structures, algorithms and provides methods to work with them. It can be viewed as containing “set of sequences & related iterators” and “methods to work with sequences of elements”.

Page | 4

Page 5: C++ & Design Patterns - primera parte

C++ STL contains data-structures or containers: vector, Vec, valarray, map, multi_map, set, multi_set, list, stack, queue, string, IO; the iterators and the algorithms.

C++ STL contains algorithms: find, find_if, count, count_if, sort, for_each, copy, unique_copy, merge etc.

1. http://www.progdoc.de/papers/adapter_binder/adapter_binder/adapter_binder.html a. Used to build functors out of ordinary “member” functions

2. STL & containers make programmers more productive.3. STL & containers make programs more robust.4. STL makes programs more maintainable and portable.5. Automatic memory management with containers – even when exception thrown.6. Containers make random access & insert possible unlike arrays.7. Local array can’t be returned; container objects can be.

A FUNCTION OBJECT (FUNCTOR) Its an object to be invoked as if it were an ordinary function, usually with same syntax A functor is an object, thus it has state, as opposed to function ptr; thus carries its info

Page | 5

STANDARD TEMPLATE LIBRARY

Containers

Sequencevector

valarraystring

list

bitset

queuestack

deque

priority_queueAssociative

set & multiset

map & multimapIterators

I/P iter

O/P iter

Fwd iter

Reverse iter

Random Access iter

Algorithms

shuffle, sort, equal, for_each, search, find_if, transform, partition, rotate, reverse, swap, move, fill,

remove, remove_if

FunctorsGenerators

Predicates

Allocators

Adapters (bind) mem_fun, mem_fun_ref, const_mem_fun_ref_t

Page 6: C++ & Design Patterns - primera parte

Achieved by overloading function call operator () functor is typically used in writing callback functions and for synthesizing functions at

runtime. Performance: can be in-lined C++ language provides 2 base classes to derive standard functors:

o unary_function<Arg,Res> and binary_function<Arg1,Arg2,Res>o More on page 509 Stroustrup

for_each, count_if, less, less_than, generate, multiplies<>, plus<>,minus<>,not1<>,not2<>.

18.1 Lambda expressions (local functions stuff)18.2 Suppose we want to apply a function to all the elements of a vector. We can define the function locally, since it is a type definition. It can take any context it needs in the constructor, and store it internally.

18.3 function addOffset(vector<int>& v, int n)

18.4 {

18.5 // we want to add n to each element of v

18.6 struct AddN : public unary_function<int>

18.7 { AddN(int n) : _n (n) {};

18.8 int operator() (const int& k) { return k + n; }

18.9 };

18.10 transform (v.begin(), v.end(), v.begin(), AddN(n));

18.11 }

C – C++ MAIN DIFFERENCES :

19.1 const objects at file scope are static in C++ but extern in C

REFERENCE :A reference is an alias to an object. As such, it needs to be initialized upon creation and cannot be reinitialized. References simplify passing of objects between function calls. A function returning a reference can also be used as l-value in C++.

INLINE: Keyword ‘inline’ is a request to compiler to optimize cost of function call by expanding object code of inline-d method at calling locations, instead of loading function parameters on stack and adding jump instructions – like macro! http://www.parashift.com/c++-faq/inline-and-perf.html Could cause “code bloat” but speeds up execution. If compiler honors too many inline-s, code bloat could increase paging thereby slowing

execution! Functions that are large or have loops, recursion, are not inline-d by compiler. Small functions declared within class body in header file are default checked for inline-ing.

MUTABLE :Keyword ‘mutable’ allows us to differentiate ‘bitwise’ const that compiler follows from ‘logical’ const. This is done by declaring class members mutable. The mutable class members are modifiable even

Page | 6

Page 7: C++ & Design Patterns - primera parte

when the object or a member function is const. Rather use mutable than a const_cast<> over the whole object.

INITIALIZATION LIST :Constructors should always use initialization list to initialize members of object. There are 2 reasons to prefer this:

1) Efficiency / Performance: Because the object is not yet created, initialization list forces creation of object directly into new memory rather than first creating temp object and then copying. Copying is also error prone.

2) const static class members can only be initialized thru initialization list.3) Exceptions: Cyclic-referential initialization, conditional initialization, throwing exception during

initialization…

if ( int *p = new (nothrow) int[100000] ) { // Use p} else { // no memory, since new returned 0 instead of throwing bad_alloc exception}

C++ CASTS : static_cast<type>(param): Plain C-style cast, without checking casting type validity const_cast<type>(param): “cast away” const-ness of an object’s context dynamic_cast<type>(param): Can cast from polymorphic virtual base class to a derived

class. Cost associated with validity check (strcmp of class names along inheritance hierarchy); Can’t cast from void*. Can throw a bad_cast exception.

reinterpret_cast<type>(param): Allows for conversion between pointer type and integer. Risky.

CPPUNIT : http://www.cs.nmsu.edu/~jeffery/courses/371/cppunit/cppunit_cookbook.html

Testcase:To make a simple test, here is what you do:Subclass the TestCase class. Override the method runTest(). When you want to check a value, call CPPUNIT_ASSERT(bool) in runTest() and pass an expression that is true if test succeeds.For example, to test the equality comparison for a Complex number class, write:class ComplexNumberTest : public CppUnit::TestCase { public: ComplexNumberTest( std::string name ) : CppUnit::TestCase( name ) {} void runTest() { CPPUNIT_ASSERT( Complex (10, 1) == Complex (10, 1) ); CPPUNIT_ASSERT( !(Complex (1, 1) == Complex (2, 2)) ); }};

Fixture:A fixture is a known set of objects that serves as a base for a set of test cases. Fixtures come in very handy when you are testing as you develop.class ComplexNumberTest : public CppUnit::TestFixture {private: Complex *m_10_1, *m_1_1, *m_11_2;public: void setUp() { m_10_1 = new Complex( 10, 1 ); m_1_1 = new Complex( 1, 1 );

Page | 7

Page 8: C++ & Design Patterns - primera parte

m_11_2 = new Complex( 11, 2 ); }

void tearDown() { delete m_10_1; delete m_1_1; delete m_11_2; }};

DESIGN PATTERNS : 26.1 REUSE. Design patterns are proven solutions to recurring/common software design problems.

Design patterns speed up development process by providing tested, proven development paradigms. Using design patterns prevent subtle issues that cause major problems later. It also improves code readability for coders familiar with the patterns. Design Patterns are classified in categories (see below). Design Patterns are described using concept of Delegation, Aggregation and Consultation.

Few Design Pattern Audio Tutorials >> OO Design.com: Design Patterns & Other OO Topics << Wikipedia: Design Patterns Observer observable design pattern (strictly 1-way ‘update’/comm from observable obj to set of observers) Observer design pattern (maintain list of dependants/observers and automatically notify state change to them) Developer.com: What are Design Patterns Moock.org: Design Pattern Intro YoLinux: Singleton (Good Design Patterns references at the end of page) EBusinessWare.com: Multi-threaded Singleton (MULTI THREADING SCENARIO W/ SINGLETON) http://www.exciton.cs.rice.edu/javaresources/designpatterns/

26.2 Creational Design Patterns:

Singleton - Ensure that only one instance of a class is created and Provide a global access point to the object.When to Use , Common Usage , Example: Lazy Singleton in Java, Example: Early Singleton in Java

Factory(Simplified version of Factory Method) - Creates objects without exposing the instantiation logic to the client and Refers to the newly created object through a common interface.When to Use , Common Usage

Document Application Example Factory Method - Defines an interface for creating objects, but let subclasses to decide which class to instantiate and Refers to the newly created object through a common interface.When to Use , Common Usage

Page | 8

Page 9: C++ & Design Patterns - primera parte

Look & Feel Example Abstract Factory - Offers the interface for creating a family of related objects, without explicitly specifying their classes. When to Use , Common Usage , Example: Gui Look & Feel in Java

Text Converter Example Builder - Defines an instance for creating an object but letting subclasses decide which class to instantiate and Allows a finer control over the construction process.Example: Text Converter in Java

Prototype - Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Database Example Object Pool - reuses and shares objects that are expensive to create..When to Use , Common Usage , Sourcecode: Database Connection Pool in Java

26.3 Behavioral Design Patterns:

Chain of Responsibiliy - It avoids attaching the sender of a request to its receiver, giving this way other objects the possibility of handling the request too.- The objects become parts of a chain and the request is sent from one object to another across the chain until one of the objects will handle it. Sourcecode:

Restaurant Example Command - Encapsulate a request in an object, Allows the parameterization of clients with different requests and Allows saving the requests in a queue. Sourcecode: Buying/Selling stocks in Java

Interpreter - Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language / Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design Sourcecode: Romans Numerals Converter in Java

Iterator - Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. Sourcecode: Java Iterator

Page | 9

Page 10: C++ & Design Patterns - primera parte

Mediator - Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. Sourcecode:

News Publisher Example Observer - Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Sourcecode: News Publisher in Java

Robot Example Strategy - Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Sourcecode: Robot Application in Java

Travel Example Template Method - Define the skeleton of an algorithm in an operation, deferring some steps to subclasses / Template Method lets subclasses redefine certain steps of an algorithm without letting them to change the algorithm's structure. Sourcecode: Travel Agency Application in Java

Customers Example Visitor - Represents an operation to be performed on the elements of an object structure / Visitor lets you define a new operation without changing the classes of the elements on which it operates. Sourcecode: Customers Report Example

Null Object - Provide an object as a surrogate for the lack of an object of a given type. The Null Object Pattern provides intelligent do nothing behavior, hiding the details from its collaborators. Sourcecode:

26.4 Structural Design Patterns:

Adapter - Convert the interface of a class into another interface clients expect. / Adapter lets classes work together, that could not otherwise because of incompatible interfaces.

Bridge - ?? Object Persistence Api in Java

Page | 10

Page 11: C++ & Design Patterns - primera parte

Shapes Example Composite - Compose objects into tree structures to represent part-whole hierarchies. / Composite lets clients treat individual objects and compositions of objects uniformly. Sourcecode: Shapes Example in Java

GUI Example Decorator - add additional responsibilities dynamically to an object. Sourcecode: Gui Application Example

Wargame Example Flyweight - use sharing to support a large number of objects that have part of their internal state in common where the other part of state can vary. Sourcecode: Java Wargame Example

Calculator Example

Memento - capture the internal state of an object without violating encapsulation and thus providing a mean for restoring the object into initial state when needed.Source Code: Calculator Example in Java

Image Viewer Proxy - provide a “Placeholder” for an object to control references to it. Sourcecode: Proxy Pattern in Java

Reactor?

Proactor?

Asynchronous Completion Token?

Acceptor-Connector?

Page | 11

Page 12: C++ & Design Patterns - primera parte

Page | 12

DESIGN PATTERNS

CREATIONAL PATTERNS:deals with object creation suitably

{Delegation}

Abstract Factory

Factory Method

Builder

Lazy Init

Object Pool

Singleton

Multiton

RAIISTRUCTURAL PATTERNS:simplifies realizing of relationships between

entities{Aggregation}

Adapter/Wrapper

Bridge

Composite

Proxy

BEHAVIORAL PATTERNS:

identify common communication

patterns between objects

{Consultation}

Chain of Responsibility

Commands

Iterator

Mediator

Memento

Blackboard

Observer

Pub/Sub

CONCURRRENCY PATTERNS:

deals with multi-threading

{Concurrency}

Active Object

Binding Properties

Event-Based Async

Balking

Monitor Obj

Scheduler

Reactor

Lock

Thread-Specific Storage

R/W Lock

Page 13: C++ & Design Patterns - primera parte

26.5

26.6 Creational Patterns – Deals with object creation mechanism suitably

26.6.1 Singleton /Multiton: Ensure only one/named globally accessible instance for a class (Logger class, Super User class; System State class; anywhere a Global variable is needed)

It's a design pattern to restrict instantiation of a class to only one object that is usually globally accessible.

o Do declare constructors private, thus denying direct creation.o A static function CreateInstance to create object indirectly.o Two static members, one holding current # instances and another, the maximum

allowed.o Life of a singleton object = duration of application.o http://www.yolinux.com/TUTORIALS/C++Singleton.html o The way to make Singleton multi-thread safe => Double checked lockingclass MySingleton {

private:MySingleton() {}//static int numInst, maxNumInst;static MySingleton *_objPtr;

public:static MySingleton* GetInstance() {

if ( _objPtr == NULL ) {boost::scoped_lock lock(&Mutex);

// Following check to guard since lock() itself is not atomicIf ( _objPtr == NULL ) {

_objPtr = new MySingleton;numInst ++;

}}return _objPtr;

}~Mysingleton() { --numInst; }

};// Initialize Singleton staticsInt MySingleton::numInst = 0;Int MySingleton::maxNumInst = 1; // pure singleton

// Create the Singleton instanceMysingleton singleObjPtr = MySingleton::GetInstance();

Avoids global namespace pollution and allows lazy allocation. Method : (1) Make constructor protected to control instantiation, and (2) Create instance of the

class only first time and return the same instance’s reference subsequently. Multi-threading : If multiple threads execute creation method at the same time, they both must

check if instance already exists. Further, creation method should be mutexed/synchronized.

26.6.2 Abstract Factory: Provides interface to create families of related objectsi) Identify rules for instantiating different objects (rule: high res display, low res display.)ii) Create an abstract base class = interface consisting of a method for creating each object (class ResFactory { virtual getDispDriver()=0; virtual getPrintDriver()=0; })iii) Implement concrete classes using this class – one for each family(class LowRes:ResFactory … implements low res display methods: getDispDriver, getPrintDriver)(class HighRes:ResFactory … implements high res display methods: getDispDriver, getPrintDriver)

Page | 13

Page 14: C++ & Design Patterns - primera parte

26.6.3 Factory Method: Provide object creation interface but let subclasses decide class to instantiate (defer instantiation to subclass) (toy factory – which toy to make is specialized)

26.6.4 Builder: Separate construction from representation of object for reuse

26.6.5 Lazy Initialization

26.6.6 Object pool: Recycle freed objects to avoid reallocation/freeing

26.6.7 Prototype: Provide schema/prototype to be copied for object creation (Templates?)

26.6.8 RAII: Tie “lifespan of object” to “resources” for confirmed resource release

26.6.9 (boost::scoped_lock, boost::shared_ptr)

26.7 Structural Patterns – Identifies relations between objects

26.7.1 Adapter/Wrapper: Convert incompatible interface across classes – Way to create new interface for a class that does right stuff but has wrong interface (Some read-only XXCircle class needs to support polymorphic methods with your Shape class –inherit new wrapper class Circle from Shape, have it contain private XXCircle object that does the work; travelling abroad with electrics) * Object Adapter Pattern (XXCircle); * Class Adapter Pattern (aka Multiple Inheritance)

26.8 Bridge: Decouple Abstraction from its many Implementation s (so they can change independently. View implementations outside of objects.) (Supporting multiple ways to draw same object, Shape inheritance (Abstraction) can decouple from Draw inheritance (Implementation) UML

26.8.1 Composites (Common abstract class providing debugging, serialization etc (Java AWT, MS MFC (CObject)))

26.8.2 Decorator: Dynamically attach additional responsibilities to an object (don’t inherit!)Decorators represent a powerful alternative to inheritance. Inheritance adds functionality to classes at compile time, decorators add functionality to objects at runtime. (Java Annotations)

Page | 14

Page 15: C++ & Design Patterns - primera parte

26.8.3 Façade: Provide high-level interfaces to subsystems - To simplify use of existing complex system by defining new/limited interface to it through new class(s) & have it use existing system. (track system usage; swap-out systems)

26.8.4 Flyweight: Use sharing across numerous fine-grained objects efficiently

26.8.5 Proxy: Surrogate/Placeholder for another object’s access (Create stub with same interface when original object is hard to create)

26.9

26.10Behavioral Patterns – Identify common communication patterns between objects

26.10.1 Chain of responsibility: Chain sender to series of receiving objects (Coin counting slotting machine)

26.10.2 Command: Encapsulate request as object

26.10.3 Interpreter: Represent & interpret a given language’s grammar (Language Translator)

26.10.4 Mediator: Loose coupling among set of objects (Format converters/Transcoders)

26.10.5 Memento: Externalize /Capture internal state of object for later restoration w/t violating encapsulation (like Restorer pattern…) (Undo history preserves internal answers separately)

26.10.6 Observer/Publisher/Subscriber: One-to-many ‘dependency’ between objects , such that when one changes, many other observing objects get notified & then update themselves

26.10.7 Blackboard: System-wide R/W info communication (Travel Reservation System)

26.10.8 Visitor: Defines new operation w/t modifying classes of objects on which it operates

26.10.9 Strategy: Choose implementation of an algorithm at runtime

26.10.10 Model-View-Controller : Model: Central component, main functions “business logic” View: Only output representation-s; Convert commands from Controller to display on a UI; Facilitates

multiple views of same data Controller: Accepts user inputs and converts to commands for Model or View (Java Spring)

Page | 15

Page 16: C++ & Design Patterns - primera parte

26.10.11 <Many others omitted here>

26.11Concurrency Patterns – Deals with multi-threaded paradigms

26.11.1 Wikipedia: All Concurrency Patterns

26.11.2 Active Object: Decouples method execution from method invocation (Event Handler/Executor)

26.11.3 Monitor Object: Approach to synchronize tasks when they use shared resource

26.11.4 Scheduler: Explicitly control execution of single-threaded code

26.11.5 Thread Pool: Idea is, thread creation and destruction takes the most time. So keep one or more pools of threads and reuse threads (realistic Thread Pool fundes)

26.11.6 Balking Design Pattern: Is when the object (toilet) is not in an appropriate state to execute a method (already auto-flushing), then ability to "safely ignore" another method call (manual flush).'

26.11.7 DCLP: (Double checked locking pattern) is a joke: pInst = new Singleton; // Can transform into following: pInst = // Step 3, assign

operator new (sizeof(Singleton)); // Step 1, allocate new (pInst) Singleton; // Step 2, construct

Dr Dobbs: DCLP is a joke (part 1) Dr Dobbs: DCLP is a joke (part 2)

<Reactor, Lock, R/W Lock, Binding Properties…>

Reactor?

Proactor?

Asynchronous Completion Token?

Acceptor-Connector?

EXPLICITLY DISALLOW USE OF COMPILER GENERATED FUNCTIONS :class Uncopyable { protected: // allow construction

Uncopyable() {} // and destruction of ~Uncopyable() {} // derived objects...

private:Uncopyable(const Uncopyable&); // ...but prevent copyingUncopyable& operator=(const Uncopyable&);

};To keep HomeForSale objects from being copied, all we have to do now is inherit from Uncopyable:class HomeForSale: private Uncopyable { // class no longer ... // declares copy ctor or}; // copy assign. operator

Page | 16

Page 17: C++ & Design Patterns - primera parte

C++ & JAVA QUICK COMPARISON :Name some major differences between C++ and Java: C++ has pointers; Java does not. Java is platform-independent; C++ is not. Java has garbage collection; C++ does not. Java does have pointers (“references”). In fact all variables in Java are pointers. The difference is that Java does not allow you to manipulate the addresses of the pointer (does not have pointer arithmetic).

NEW IN C++11 : here1. auto – automatic type inference at variable declaration2. nullptr – null pointer type; implicitly convertible to NULL pointer & false but not integer 03. Range-based for loops – iterates array, init-list, or anything for which begin(), end() works

for(const auto& i : arr) ++i; … for(auto mapItem : map) cout << mapIter.first;4. Override and final

class B { virtual void f(short) {…};};class D: B { virtual void f(int) override {…}}; //Intent specifiable to override B::f(short)

class E: B { virtual void f(int) final {…} }; //E’s derived classes can NOT override E::f(int)5. Strongly-typed enums – tranditional enums export names to enclosing scope & convert to int

implicitly. New enums don’t.enum class Signal { Red, Yellow, Green };

6. Smart pointers – unique_ptr – doesn’t have copy ctor but has move ctor– shared_ptr – RCSP– weak_ptr – holds references but doesn’t update ref_count, thus allowing cycles to

break7. Lambdas – auto is_odd = [](int n) {return n%2==1;}; auto pos = find_if(begin(v), end(v), is_odd);

8. non-member begin() and end() – (see above)9. static_assert and type traits – assert at compile time: static_assert(i < 3, "i is too small");10. Move semantics – if object being copied using copy ctor or = operator is temporary, optimizes by

using move ctor or move = operator.C (const C&& c); // move constructorC& operator=(C&& c); // move assignment operator

11. constexpr – allows declaring constant expression, with user defined types at compile time12. decltype(expr) – returns the type of an expression13. std::initializer_list – init lists more types than just arrays: void f(initializer_list<int>); f({1,2}); or

f({}); or f{1,2};14. In-class member initialization – class X { private: int a(0); } // So each ctor won’t have to do.

OTHER WORTHY REFERENCES : C++ Standard Template Library – for C++ Smart Pointers An abstract data-type that simulates a pointer and provides features like automatic

garbage collection or bounds checking. It performs automatic deallocation of the object when it goes out of scope or when no references to a memory exists. Many types – RCSP (Resource counting…) or assigning object ownership to one pointer (auto_ptr: prev object looses ownership & ptr value). Can be implemented by overloading dereferencing and assignment operator overloading. C++ auto_ptr, tr1::shared_ptr templates. auto_ptr <==> RAII: Resource Acquisition Is Initialization. shared_ptr is alternative.

std::auto_ptr is neither Assignable nor CopyConstructible.Object *o1 = new Object(); Object *o2 = new Object();auto_ptr<Object> sp1 = o1; // o1.count == 1auto_ptr<Object> sp2 = o2; // o2.count == 1sp2 = sp1; // o1.count == 2, o2.count == 0 => o2 will be deleted heresp2 = NULL; // o1.count == 1sp1 = new Object(); // o1.count == 0, the o1 object deleted hereo2 = new Object; return; // memory leak!

Page | 17

Page 18: C++ & Design Patterns - primera parte

Boost::shared_ptr<> techniques – very good. Jist of which is below… C++ Technical Report 1 , a document proposing additions to the C++ Standard Library Boost C++ Libraries , a set of free peer-reviewed portable C++ ST libraries www.boost.org C++0x , is an unofficial name for a planned new standard for C++ language C++ FAQ Lite by Marshall Cline http://www.stardeveloper.com/articles/display.html?article=2004022804&page=1 (Good info) http://www.yolinux.com/TUTORIALS/LinuxTutorialC++.html http://www.infernodevelopment.com/c-

pthreads-api

On some platforms and compilers, double can exactly represent all integer values in the range 0 to 1e8, inclusive, but float cannot .

boost::shared_ptr<>: R.C.S.P.shared_ptr<int> p(new int(5));weak_ptr<int> q(p);if ( int *r = q.get() ) p.reset();---- A shared_ptr uses reference counting to determine when the object pointed to is no longer needed.

Then, the object is automatically deleted. Each shared_ptr destructor call decrements the bound pointer's reference count. When the

reference count reaches 0, the pointer is deleted. This is done by overloading -> and * operators. shared_ptr meets CopyConstructible and Assignable requirement of C++ STL => possible cycles of shared

instances can’t be reclaimed (due to reference counting). A weak_ptr<> is like shared_ptr, but it avoid reference cycles. use_count() member function gets number of current references. Same level of thread safety as built-in ptrs. no news here => multiple reads, single writes => OK shared_ptr constructor with 2 args takes 2nd arg as deleter operator. If we want shared_ptr for an EXISTING object so that shared_ptr doesn't try to delete the object, then use a

custom deleter (functor) that does nothing:struct null_deleter { void operator()(void const *) {}};

static X my_static_obj;

shared_ptr<X> createMyX() { shared_ptr<X> px(&my_static_obj, null_deleter()); return px;};

shared_ptr<> can be used to implement PIMPL Idiom (also called Handle/Body idiom - hiding implementation) (PIMPL = “Pointer To Implementation”)

Use shared_ptr<> pointing to an 'incomplete class' for opaque handling of data (encapsulation).In following example, the need for a typical fclose() is avoided.Without shared_ptr<>:

class FILE; // incomplete class (like Object in Java?)FILE * fopen(......);void fread(FILE *fp, ......);void fclose(FILE *fp);

WITH shared_ptr<>:class FILE;shared_ptr<FILE> fopen (......);void fread(shared_ptr<FILE> fp, .......);

This works because shared_ptr is able to execute a 'custom deleter', so explicit call to fclose(fp)is not needed. Further, copying (sharing) as well as deletion of 'incomplete' class is POSSIBLE in C++.

PREVENTING client code from deleting a pointer that is being managed by shared_ptr (disallowing "delete SP.get();" when SP is a shared_ptr):Deletion of incomplete types can cause silent hard to track bugs.Approach 1: Use a protected destructor.Approach 2: Use a private deleter (like Singleton pattern): class X {

Page | 18

Page 19: C++ & Design Patterns - primera parte

private:~X();class deleter;friend class deleter;class deleter { public: void operator()(X* p) { delete p; } };

public:static shared_ptr<X> create() {

shared_ptr<X> px(new X, X::deleter());return px;

} };

Execute some function / cleanup code f(x,y) upon when a block finishes: shared_ptr<void> tempo(static_cast<void*>(0), bind(f, x, y));

[35.18] Why am I getting errors when my template-derived-class uses a nested type it inherits from its template-base-class? Click here to go to the next FAQ in the "chain" of recent changes.

Perhaps surprisingly, the following code is not valid C++, even though some compilers accept it:

 template<typename T> class B { public:

   class Xyz { ... };  ← type nested in class B<T>

   typedef int Pqr;    ← type nested in class B<T> };  template<typename T> class D : public B<T> { public:   void g()   {

     Xyz x;  ← bad (even though some compilers erroneously (temporarily?) accept it)

     Pqr y;  ← bad (even though some compilers erroneously (temporarily?) accept it)   } };

This might hurt your head; better if you sit down.

Within D<T>::g(), name Xyz and Pqr do not depend on template parameter T, so they are known as a nondependent names. On the other hand, B<T> is dependent on template parameter T so B<T> is called a dependent name.

Here's the rule: the compiler does not look in dependent base classes (like B<T>) when looking up nondependent names (like Xyz or Pqr). As a result, the compiler does not know they even exist let alone are types. At this point, programmers sometimes prefix them with B<T>::, such as:

 template<typename T> class D : public B<T> { public:   void g()   {

     B<T>::Xyz x;  ← bad (even though some compilers erroneously (temporarily?) accept it)

     B<T>::Pqr y;  ← bad (even though some compilers erroneously (temporarily?) accept it)   } };

Unfortunately this doesn't work either because those names (are you ready? are you sitting down?) are not necessarily types. "Huh?!?" you say. "Not types?!?" you exclaim. "That's crazy; any fool can SEE they are types; just look!!!" you protest. Sorry, the fact is that they might not be types. The reason is that there can be a specialization of B<T>, say B<Foo>, where B<Foo>::Xyz is a data member, for example. Because of this potential specialization, the compiler cannot assume that B<T>::Xyz is a type until it knows T. The solution is to give the compiler a hint via the typename keyword:

Page | 19

Page 20: C++ & Design Patterns - primera parte

 template<typename T> class D : public B<T> { public:   void g()   {

     typename B<T>::Xyz x;  ← good

     typename B<T>::Pqr y;  ← good   } };

Quick Tips: Closure : Ability to define (inner) functions locally within other (outer) functions. Inner

function can access local variables of outer (enclosing) function. Provides scoping. Currying : Curried functions are functions of more than one arguments that take “one

argument at a time”, instead of taking all arguments together. Debug running process: gdb –pid=<PID>: gdb will halt the process right there & load Gdb tutorial on de-referencing STL containers Handy Macros to have while working with C++ STL

o alloca (): allocates space in the local stack frame of caller, causing automatic free-ing on longjump/return. compelling speed advantages and thread-safe, but error-prone and costly stack-size querying needed. Also, sometimes you don’t want freeing to allow debugging/exception handling…

o typedef vector<int> vi; o typedef vector<vi> vvi;

o typedef pair<int,int> ii; o #define sz(a) int((a).size())

o #define pb push_back o #defile all(c) (c).begin(),(c).end()

o #define tr(container, it) for(typeof(container.begin()) it = container.begin(); it != container.end(); it++)o #define present(c,x) ((c).find(x) != (c).end())

o #define cpresent(c,x) (find(all(c),x) != (c).end())

o Compiler Name Mangling Mangling schemes : cdecl: (Win Console) just prepends “_”; stdcall: (Win32 WinAPI)

_name@#bytes_params; fastcall: @name@#bytes_params Utils : c++filt, undname, nm, nm --demangle|-C, Win: “dumpbin /symbols”

If NDEBUG is defined (above #include assert.h), assert(0 macro does nothing (disabled). The Named Constructor Idiom is used to control object construction [eg: point->polar(1.1,2.2) v/s

point->cartesian(1.1,2.2)]. It can also be used to make sure your objects are always created via new. http://codewrangler.home.comcast.net/~codewrangler/tech_info/patterns_code.html http://www.codesampler.com/miscsrc.htm >>> http://www.netobjectives.com/resources/books/design-patterns-explained/cpp-code-examples Open-Close Principle: Software entities like classes, modules and functions should be open for extension but closed

for modifications. Likov's Substitution Principle: If a program module is using a Base class, then the reference to the Base class

can be replaced with a Derived class without affecting the functionality of the program module. [25.15] What is the exact order of destructors in a multiple and/or virtual inheritance situation?

Short answer: the exact opposite of the constructor order.

Long answer: suppose the "most derived" class is D, meaning the actual object that was originally created was of class D, and that D inherits multiply (and non-virtually) from B1 and B2. The sub-object corresponding to most-derived class D runs first, followed by the dtors for its non-virtual base classes in reverse declaration-order. Thus the destructor order will be D, B2, B1. This rule is applied recursively; for example, if B1 inherits from B1a and B1b, and B2 inherits from B2a and B2b, the final order is D, B2, B2b, B2a, B1, B1b, B1a.

After all this is finished, virtual base classes that appear anywhere in the hierarchy are handled. The destructors for these virtual base classes are executed in the reverse order they appear in a depth-first left-to-right traversal of the graph of base classes, where left to right refer to the order of appearance of base class names. For instance,

Page | 20

Page 21: C++ & Design Patterns - primera parte

if the virtual base classes in that traversal order are V1, V1, V1, V2, V1, V2, V2, V1, V3, V1, V2, the unique ones are V1, V2, V3, and the final-final order is D, B2, B2b, B2a, B1, B1b, B1a, V3, V2, V1.

TYPICAL INTERVIEW TOPICS TO PREPARE

1. New in C++11: include most of TR1, extend STL rather than core, better type safety, constexpr, extern (build speedup) & var-arg templates, type inference (auto TYPE ID), init-list, anon (lambda) fn, closure, =default & =delete for C’tors, tuple, regex

2. OOD principles – Book + Live Mesh + Google search3. C++ & STL – MMS C++ notes + Trial programs + Online interview questions + Books + Live Mesh4. The “Programming interview exposed” book5. Algorithms & Data-structures – Cormen + CareerCup + Google search6. CareerCup & TopCoder & FAQ Lite

7. http://www.indiabix.com/technical/interview-questions-and-answers/

Page | 21