Page | 1
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& DATAENCAPSULATION.......................................................................................................................................... 5
9 POLYMORPHISM: (types)............................................................................................................................................................... 6
10 TEMPLATE............................................................................................................................................................................... 6
11 DYNAMIC BINDING / VIRTUAL FUNCTION................................................................................................................................... 6
12 ABSTRACTBASECLASS ............................................................................................................................................................. 7
13 NAMESPACE............................................................................................................................................................................ 7
14 EXCEPTION HANDLING: (types –by value, reference, type).......................................................................................................... 7
15 CONTAINERS........................................................................................................................................................................... 7
16 STANDARD TEMPLATELIBRARY................................................................................................................................................. 7
17 AFUNCTION OBJECT(FUNCTOR)............................................................................................................................................... 8
18 C –C++ MAIN DIFFERENCES...................................................................................................................................................... 9
19 REFERENCE............................................................................................................................................................................. 9
20 MUTABLE................................................................................................................................................................................ 9
21 INITIALIZATIONLIST................................................................................................................................................................. 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 EXPLICITLYDISALLOW USEOF COMPILER GENERATED FUNCTIONS............................................................................................. 19
26 C++& JAVAQUICK COMPARISON............................................................................................................................................ 20
Page | 2
Good Sources:
2.1 C++ FAQLite MarshallCline
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 | 3
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 | 4
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, listetc.
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 | 5
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
STANDARD
TEMPLATE
LIBRARY
Containers
Sequence
vector
valarray
string
list
bitset
queue
stack
deque
priority_queue
Associative
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
Functors
Generators
Predicates
Allocators
Adapters (bind) mem_fun, mem_fun_ref,
const_mem_fun_ref_t
Page | 6
 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.
function addOffset(vector<int>& v, int n)
{
// we want to add n to each element of v
struct AddN : public unary_function<int>
{ AddN(int n) : _n (n) {};
int operator() (const int& k) { return k + n; }
};
transform (v.begin(), v.end(), v.begin(), AddN(n));
}
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 fileare 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 | 7
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 listforces 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] ) {
// Usep
} else {
// no memory, sincenew 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 iswhatyoudo:
Subclass the TestCase class.Override the methodrunTest(). Whenyou wantto check a value,
call CPPUNIT_ASSERT(bool)inrunTest() andpassanexpressionthatistrue if testsucceeds.
For example,totestthe equalitycomparisonforaComplex numberclass,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 isaknownsetof objectsthatservesasa base fora setof test cases.Fixturescome in
veryhandywhenyouare testingasyoudevelop.
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 | 8
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 provensolutionsto recurring/common software design
problems.
 Design patterns speed updevelopment process byproviding tested, proven development paradigms.
 Using design patterns prevent subtle issues that cause major problems later.
 It alsoimproves code readabilityfor coders familiar withthe patterns.
 Design Patterns are classifiedincategories(see below).
 Design Patterns are described using concept of Delegation, Aggregationand 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 DesignPatterns
 Moock.org: Design Pattern Intro
 YoLinux: Singleton (Good DesignPatterns references at the end ofpage)
 EBusinessWare.com: Multi-threaded Singleton (MULTI THREADING SCENARIO W/ SINGLETON)
 http://www.exciton.cs.rice.edu/javaresources/designpatterns/
26.2 Creational DesignPatterns:
Singleton- Ensure that onlyone instance of a class iscreated and Provide a global access
point to the object.WhentoUse , Common Usage , Example:Lazy SingletoninJava, Example:Early
SingletoninJava
Factory(SimplifiedversionofFactory Method) - Creates objectswithout exposingthe
instantiationlogic to the clientand Refersto the newlycreated objectthrough a common
interface.WhentoUse , CommonUsage
Document ApplicationExample FactoryMethod - Definesan interface for
creating objects,but letsubclassesto decide whichclass to instantiate and Refersto the newly
created objectthrough a common interface.WhentoUse , CommonUsage
Page | 9
Look & Feel Example AbstractFactory - Offersthe interface for creating a
familyof relatedobjects,without explicitlyspecifyingtheirclasses. WhentoUse , Common
Usage , Example: Gui Look & Feel inJava
Text ConverterExample Builder- Definesaninstance for creating an object
but lettingsubclassesdecide whichclass to instantiate and Allowsa finercontrol over the
construction process.Example:TextConverterin Java
Prototype - Specifythe kindsof objects to create usinga prototypical instance, and
create newobjects by copyingthis prototype.
Database Example ObjectPool - reusesand shares objectsthat are expensive
to create..Whento Use , CommonUsage , Sourcecode:Database ConnectionPool in Java
26.3 Behavioral DesignPatterns:
Chain of Responsibiliy- Itavoids attaching the senderof a requestto itsreceiver,giving
this way other objectsthe possibilityofhandlingthe requesttoo.
- The objectsbecome parts of a chain and the requestis sentfrom one objectto another across the
chain until one of the objects will handle it. Sourcecode:
Restaurant Example Command- Encapsulate a requestin an object, Allows
the parameterizationof clientswithdifferentrequestsandAllows savingthe requestsin a queue.
Sourcecode:Buying/Sellingstocksin Java
Interpreter- Givena language,define a representationforits grammar along with an
interpreterthat uses the representationto interpretsentencesinthe language / Map a domain to a
language,the language to a grammar, and the grammar to a hierarchical object-orienteddesign
Sourcecode:Romans Numerals ConverterinJava
Iterator - Provide a way to accessthe elementsofan aggregate objectsequentially
without exposingitsunderlyingrepresentation. Sourcecode:JavaIterator
Page | 10
Mediator- Define an object that encapsulateshow a setof objectsinteract. Mediator
promotesloose coupling by keepingobjectsfromreferringto eachother explicitly,andit lets you vary
theirinteraction independently. Sourcecode:
NewsPublisherExample Observer- Define aone-to-manydependency
betweenobjectsso that when one object changesstate, all its dependentsare notifiedandupdated
automatically. Sourcecode:NewsPublisherinJava
Robot Example Strategy- Define a family of algorithms, encapsulate each
one,and make them interchangeable.Strategylets the algorithm vary independentlyfromclientsthat
use it. Sourcecode:Robot Applicationin Java
Travel Example Template Method- Define the skeletonof an algorithm inan
operation,deferringsome stepsto subclasses/ Template Method letssubclassesredefine certain
stepsof an algorithmwithout lettingthem to change the algorithm'sstructure. Sourcecode:Travel
Agency ApplicationinJava
CustomersExample Visitor- Representsan operation to be performedon the
elementsofan object structure / Visitorlets you define anew operationwithout changing the classes
of the elementsonwhichit operates. Sourcecode:CustomersReport Example
Null Object - Provide an objectas a surrogate for the lack of an objectof a giventype.
The Null ObjectPattern providesintelligentdonothingbehavior,hiding the detailsfrom its
collaborators. Sourcecode:
26.4 Structural DesignPatterns:
Adapter - Convertthe interface of a class into another interface clientsexpect./ Adapter
letsclasses work together,that could not otherwise because of incompatible interfaces.
Bridge - ?? Object Persistence Api inJava
Page | 11
ShapesExample Composite - Compose objectsinto tree structures to
representpart-whole hierarchies./ Composite letsclientstreat individual objectsand compositionsof
objectsuniformly. Sourcecode:Shapes Example in Java
GUIExample Decorator - add additional responsibilitiesdynamicallytoan
object. Sourcecode:Gui ApplicationExample
Wargame Example Flyweight- use sharingto support a large numberof
objectsthat 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 ofan objectwithout violatingencapsulation
and thus providinga mean for restoringthe objectinto initial state whenneeded.Source
Code:Calculator Example inJava
Image Viewer Proxy- provide a “Placeholder” foran objectto control
referencestoit. Sourcecode:Proxy Pattern in Java
Reactor?
Proactor?
Asynchronous Completion Token?
Acceptor-Connector?
Page | 12
DESIGN
PATTERNS
CREATIONAL PATTERNS:
deals with object
creation suitably
{Delegation}
Abstract Factory
Factory Method
Builder
Lazy Init
Object Pool
Singleton
Multiton
RAII
STRUCTURAL 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
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 restrictinstantiation of a classto only one object that is usually globally
accessible.
o Do declareconstructors private,thus denying direct creation.
o A static function CreateInstanceto create object indirectly.
o Two static members, one holdingcurrent# 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 locking
class MySingleton {
private:
MySingleton() {}
//static intnumInst, 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 atomic
If ( _objPtr == NULL ) {
_objPtr = new MySingleton;
numInst ++;
}
}
return _objPtr;
}
~Mysingleton() { --numInst; }
};
// Initialize Singleton statics
Int MySingleton::numInst = 0;
Int MySingleton::maxNumInst = 1; // pure singleton
// Create the Singleton instance
Mysingleton singleObjPtr = MySingleton::GetInstance();
 Avoids global namespace pollution and allows lazy allocation.
 Method: (1) Make constructor protected to control instantiation,and (2) Create instanceof the
class only firsttimeand return the same instance’s reference subsequently.
 Multi-threading:If multiplethreads execute creation method atthe sametime, they both must
check if instancealready exists.Further,creation method should be mutexed/synchronized.
26.6.2 Abstract Factory: Provides interface to create families of related objects
i) 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 | 14
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 Implementations (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. Inheritanceadds functionality to classes at compile
time, decorators add functionality to objects at runtime. (Java Annotations)
Page | 15
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
multipleviews of same data
 Controller: Accepts user inputs and converts to commands for Model or View (Java Spring)
Page | 16
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: // allowconstruction
Uncopyable() {} // and destruction of
~Uncopyable() {} // derived objects...
private:
Uncopyable(constUncopyable&); // ...but prevent copying
Uncopyable& operator=(constUncopyable&);
};
To keep HomeForSale objects from being copied, all we have to do now is inheritfrom Uncopyable:
class HomeForSale:privateUncopyable{ // class no longer
... // declares copy ctor or
}; // copy assign.operator
Page | 17
C++ & JAVA QUICK COMPARISON:
Name somemajordifferencesbetweenC++andJava: C++ has pointers; Javadoes not. Java
is platform-independent; C++ is not. Java has garbage collection;C++ does not. Javadoes have
pointers (“references”).In factall variables in Java are pointers. The differenceis that Java does
not allow youto manipulate the addresses of the pointer (does not have pointer arithmetic).
NEW IN C++11: here
1. auto – automatic type inference at variable declaration
2. nullptr – null pointer type; implicitly convertible to NULL pointer & false but not integer 0
3. 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 voidf(short) {…};};
class D: B { virtual void f(int) override {…}}; //Intent specifiable to override B::f(short)
 class E: B { virtual voidf(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
break
7. 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 constructor
C& operator=(C&& c); // move assignment operator
11. constexpr – allows declaring constant expression, with user defined types at compile time
12. decltype(expr) – returns the type of an expression
13. 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 ==1
auto_ptr<Object>sp2= o2; // o2.count ==1
sp2 = sp1; //o1.count ==2,o2.count==0 =>o2 willbe deletedhere
sp2 = NULL; // o1.count ==1
sp1 = new Object(); // o1.count ==0,theo1 object deletedhere
Page | 18
o2 = new Object; return; // memoryleak!
 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 unofficialname 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(newint(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 doneby overloading -> and * operators.
 shared_ptr meets CopyConstructible and Assignablerequirement of C++ STL => possible cycles of shared
instances can’t be reclaimed (due toreference 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: Usea protected destructor.
Page | 19
Approach 2: Usea private deleter (like Singleton pattern):
class X {
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(newX, 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? Clickhere to go to the next FAQ in the "chain" of recent changes.
Perhaps surprisingly, thefollowingcodeis not valid C++, even though somecompilers acceptit:
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 untilit knows T. The solution is to give the
compiler a hint via the typename keyword:
Page | 20
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
functioncan access localvariables of outer (enclosing) function. Providesscoping.
 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, modulesand functions shouldbe open for extensionbut 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 actualobject 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-virtualbase 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 finalorder 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 | 21
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-finalorder 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 thancore,better type safety,constexpr, extern(build speedup)
& var-arg templates,type inference (auto TYPEID),init-list, anon(lambda)fn,closure,=default & =delete for C’tors,
tuple, regex
2. OOD principles – Book + LiveMesh + Googlesearch
3. C++ & STL – MMSC++ notes + Trial programs + Onlineinterview questions+ Books + LiveMesh
4. The“Programminginterview exposed” book
5. Algorithms & Data-structures– Cormen + CareerCup + Googlesearch
6. CareerCup & TopCoder & FAQLite
7. http://www.indiabix.com/technical/interview-questions-and-answers/

C++ & Design Patterns Quicky

  • 1.
    Page | 1 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& DATAENCAPSULATION.......................................................................................................................................... 5 9 POLYMORPHISM: (types)............................................................................................................................................................... 6 10 TEMPLATE............................................................................................................................................................................... 6 11 DYNAMIC BINDING / VIRTUAL FUNCTION................................................................................................................................... 6 12 ABSTRACTBASECLASS ............................................................................................................................................................. 7 13 NAMESPACE............................................................................................................................................................................ 7 14 EXCEPTION HANDLING: (types –by value, reference, type).......................................................................................................... 7 15 CONTAINERS........................................................................................................................................................................... 7 16 STANDARD TEMPLATELIBRARY................................................................................................................................................. 7 17 AFUNCTION OBJECT(FUNCTOR)............................................................................................................................................... 8 18 C –C++ MAIN DIFFERENCES...................................................................................................................................................... 9 19 REFERENCE............................................................................................................................................................................. 9 20 MUTABLE................................................................................................................................................................................ 9 21 INITIALIZATIONLIST................................................................................................................................................................. 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 EXPLICITLYDISALLOW USEOF COMPILER GENERATED FUNCTIONS............................................................................................. 19 26 C++& JAVAQUICK COMPARISON............................................................................................................................................ 20
  • 2.
    Page | 2 GoodSources: 2.1 C++ FAQLite MarshallCline 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.
  • 3.
    Page | 3 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.
  • 4.
    Page | 4 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, listetc. 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”.
  • 5.
    Page | 5 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 STANDARD TEMPLATE LIBRARY Containers Sequence vector valarray string list bitset queue stack deque priority_queue Associative 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 Functors Generators Predicates Allocators Adapters (bind) mem_fun, mem_fun_ref, const_mem_fun_ref_t
  • 6.
    Page | 6 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. function addOffset(vector<int>& v, int n) { // we want to add n to each element of v struct AddN : public unary_function<int> { AddN(int n) : _n (n) {}; int operator() (const int& k) { return k + n; } }; transform (v.begin(), v.end(), v.begin(), AddN(n)); } 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 fileare 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
  • 7.
    Page | 7 whenthe 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 listforces 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] ) { // Usep } else { // no memory, sincenew 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 iswhatyoudo: Subclass the TestCase class.Override the methodrunTest(). Whenyou wantto check a value, call CPPUNIT_ASSERT(bool)inrunTest() andpassanexpressionthatistrue if testsucceeds. For example,totestthe equalitycomparisonforaComplex numberclass,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 isaknownsetof objectsthatservesasa base fora setof test cases.Fixturescome in veryhandywhenyouare testingasyoudevelop. 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 );
  • 8.
    Page | 8 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 provensolutionsto recurring/common software design problems.  Design patterns speed updevelopment process byproviding tested, proven development paradigms.  Using design patterns prevent subtle issues that cause major problems later.  It alsoimproves code readabilityfor coders familiar withthe patterns.  Design Patterns are classifiedincategories(see below).  Design Patterns are described using concept of Delegation, Aggregationand 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 DesignPatterns  Moock.org: Design Pattern Intro  YoLinux: Singleton (Good DesignPatterns references at the end ofpage)  EBusinessWare.com: Multi-threaded Singleton (MULTI THREADING SCENARIO W/ SINGLETON)  http://www.exciton.cs.rice.edu/javaresources/designpatterns/ 26.2 Creational DesignPatterns: Singleton- Ensure that onlyone instance of a class iscreated and Provide a global access point to the object.WhentoUse , Common Usage , Example:Lazy SingletoninJava, Example:Early SingletoninJava Factory(SimplifiedversionofFactory Method) - Creates objectswithout exposingthe instantiationlogic to the clientand Refersto the newlycreated objectthrough a common interface.WhentoUse , CommonUsage Document ApplicationExample FactoryMethod - Definesan interface for creating objects,but letsubclassesto decide whichclass to instantiate and Refersto the newly created objectthrough a common interface.WhentoUse , CommonUsage
  • 9.
    Page | 9 Look& Feel Example AbstractFactory - Offersthe interface for creating a familyof relatedobjects,without explicitlyspecifyingtheirclasses. WhentoUse , Common Usage , Example: Gui Look & Feel inJava Text ConverterExample Builder- Definesaninstance for creating an object but lettingsubclassesdecide whichclass to instantiate and Allowsa finercontrol over the construction process.Example:TextConverterin Java Prototype - Specifythe kindsof objects to create usinga prototypical instance, and create newobjects by copyingthis prototype. Database Example ObjectPool - reusesand shares objectsthat are expensive to create..Whento Use , CommonUsage , Sourcecode:Database ConnectionPool in Java 26.3 Behavioral DesignPatterns: Chain of Responsibiliy- Itavoids attaching the senderof a requestto itsreceiver,giving this way other objectsthe possibilityofhandlingthe requesttoo. - The objectsbecome parts of a chain and the requestis sentfrom one objectto another across the chain until one of the objects will handle it. Sourcecode: Restaurant Example Command- Encapsulate a requestin an object, Allows the parameterizationof clientswithdifferentrequestsandAllows savingthe requestsin a queue. Sourcecode:Buying/Sellingstocksin Java Interpreter- Givena language,define a representationforits grammar along with an interpreterthat uses the representationto interpretsentencesinthe language / Map a domain to a language,the language to a grammar, and the grammar to a hierarchical object-orienteddesign Sourcecode:Romans Numerals ConverterinJava Iterator - Provide a way to accessthe elementsofan aggregate objectsequentially without exposingitsunderlyingrepresentation. Sourcecode:JavaIterator
  • 10.
    Page | 10 Mediator-Define an object that encapsulateshow a setof objectsinteract. Mediator promotesloose coupling by keepingobjectsfromreferringto eachother explicitly,andit lets you vary theirinteraction independently. Sourcecode: NewsPublisherExample Observer- Define aone-to-manydependency betweenobjectsso that when one object changesstate, all its dependentsare notifiedandupdated automatically. Sourcecode:NewsPublisherinJava Robot Example Strategy- Define a family of algorithms, encapsulate each one,and make them interchangeable.Strategylets the algorithm vary independentlyfromclientsthat use it. Sourcecode:Robot Applicationin Java Travel Example Template Method- Define the skeletonof an algorithm inan operation,deferringsome stepsto subclasses/ Template Method letssubclassesredefine certain stepsof an algorithmwithout lettingthem to change the algorithm'sstructure. Sourcecode:Travel Agency ApplicationinJava CustomersExample Visitor- Representsan operation to be performedon the elementsofan object structure / Visitorlets you define anew operationwithout changing the classes of the elementsonwhichit operates. Sourcecode:CustomersReport Example Null Object - Provide an objectas a surrogate for the lack of an objectof a giventype. The Null ObjectPattern providesintelligentdonothingbehavior,hiding the detailsfrom its collaborators. Sourcecode: 26.4 Structural DesignPatterns: Adapter - Convertthe interface of a class into another interface clientsexpect./ Adapter letsclasses work together,that could not otherwise because of incompatible interfaces. Bridge - ?? Object Persistence Api inJava
  • 11.
    Page | 11 ShapesExampleComposite - Compose objectsinto tree structures to representpart-whole hierarchies./ Composite letsclientstreat individual objectsand compositionsof objectsuniformly. Sourcecode:Shapes Example in Java GUIExample Decorator - add additional responsibilitiesdynamicallytoan object. Sourcecode:Gui ApplicationExample Wargame Example Flyweight- use sharingto support a large numberof objectsthat 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 ofan objectwithout violatingencapsulation and thus providinga mean for restoringthe objectinto initial state whenneeded.Source Code:Calculator Example inJava Image Viewer Proxy- provide a “Placeholder” foran objectto control referencestoit. Sourcecode:Proxy Pattern in Java Reactor? Proactor? Asynchronous Completion Token? Acceptor-Connector?
  • 12.
    Page | 12 DESIGN PATTERNS CREATIONALPATTERNS: deals with object creation suitably {Delegation} Abstract Factory Factory Method Builder Lazy Init Object Pool Singleton Multiton RAII STRUCTURAL 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
  • 13.
    Page | 13 26.5 26.6Creational 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 restrictinstantiation of a classto only one object that is usually globally accessible. o Do declareconstructors private,thus denying direct creation. o A static function CreateInstanceto create object indirectly. o Two static members, one holdingcurrent# 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 locking class MySingleton { private: MySingleton() {} //static intnumInst, 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 atomic If ( _objPtr == NULL ) { _objPtr = new MySingleton; numInst ++; } } return _objPtr; } ~Mysingleton() { --numInst; } }; // Initialize Singleton statics Int MySingleton::numInst = 0; Int MySingleton::maxNumInst = 1; // pure singleton // Create the Singleton instance Mysingleton singleObjPtr = MySingleton::GetInstance();  Avoids global namespace pollution and allows lazy allocation.  Method: (1) Make constructor protected to control instantiation,and (2) Create instanceof the class only firsttimeand return the same instance’s reference subsequently.  Multi-threading:If multiplethreads execute creation method atthe sametime, they both must check if instancealready exists.Further,creation method should be mutexed/synchronized. 26.6.2 Abstract Factory: Provides interface to create families of related objects i) 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)
  • 14.
    Page | 14 26.6.3Factory 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 Implementations (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. Inheritanceadds functionality to classes at compile time, decorators add functionality to objects at runtime. (Java Annotations)
  • 15.
    Page | 15 26.8.3Faç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 multipleviews of same data  Controller: Accepts user inputs and converts to commands for Model or View (Java Spring)
  • 16.
    Page | 16 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: // allowconstruction Uncopyable() {} // and destruction of ~Uncopyable() {} // derived objects... private: Uncopyable(constUncopyable&); // ...but prevent copying Uncopyable& operator=(constUncopyable&); }; To keep HomeForSale objects from being copied, all we have to do now is inheritfrom Uncopyable: class HomeForSale:privateUncopyable{ // class no longer ... // declares copy ctor or }; // copy assign.operator
  • 17.
    Page | 17 C++& JAVA QUICK COMPARISON: Name somemajordifferencesbetweenC++andJava: C++ has pointers; Javadoes not. Java is platform-independent; C++ is not. Java has garbage collection;C++ does not. Javadoes have pointers (“references”).In factall variables in Java are pointers. The differenceis that Java does not allow youto manipulate the addresses of the pointer (does not have pointer arithmetic). NEW IN C++11: here 1. auto – automatic type inference at variable declaration 2. nullptr – null pointer type; implicitly convertible to NULL pointer & false but not integer 0 3. 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 voidf(short) {…};}; class D: B { virtual void f(int) override {…}}; //Intent specifiable to override B::f(short)  class E: B { virtual voidf(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 break 7. 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 constructor C& operator=(C&& c); // move assignment operator 11. constexpr – allows declaring constant expression, with user defined types at compile time 12. decltype(expr) – returns the type of an expression 13. 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 ==1 auto_ptr<Object>sp2= o2; // o2.count ==1 sp2 = sp1; //o1.count ==2,o2.count==0 =>o2 willbe deletedhere sp2 = NULL; // o1.count ==1 sp1 = new Object(); // o1.count ==0,theo1 object deletedhere
  • 18.
    Page | 18 o2= new Object; return; // memoryleak!  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 unofficialname 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(newint(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 doneby overloading -> and * operators.  shared_ptr meets CopyConstructible and Assignablerequirement of C++ STL => possible cycles of shared instances can’t be reclaimed (due toreference 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: Usea protected destructor.
  • 19.
    Page | 19 Approach2: Usea private deleter (like Singleton pattern): class X { 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(newX, 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? Clickhere to go to the next FAQ in the "chain" of recent changes. Perhaps surprisingly, thefollowingcodeis not valid C++, even though somecompilers acceptit: 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 untilit knows T. The solution is to give the compiler a hint via the typename keyword:
  • 20.
    Page | 20 template<typenameT> 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 functioncan access localvariables of outer (enclosing) function. Providesscoping.  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, modulesand functions shouldbe open for extensionbut 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 actualobject 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-virtualbase 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 finalorder 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,
  • 21.
    Page | 21 ifthe 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-finalorder 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 thancore,better type safety,constexpr, extern(build speedup) & var-arg templates,type inference (auto TYPEID),init-list, anon(lambda)fn,closure,=default & =delete for C’tors, tuple, regex 2. OOD principles – Book + LiveMesh + Googlesearch 3. C++ & STL – MMSC++ notes + Trial programs + Onlineinterview questions+ Books + LiveMesh 4. The“Programminginterview exposed” book 5. Algorithms & Data-structures– Cormen + CareerCup + Googlesearch 6. CareerCup & TopCoder & FAQLite 7. http://www.indiabix.com/technical/interview-questions-and-answers/