Tuesday, June 26, 2007

Use private inheritance judiciously

compilers dont convert a derived class object into a base class object automatically if you privately inherit

private inheritance means you want to exploit some features available in base class, and not that their is any conceptual relationship between them

use composition whenever you can, use private inheritance when you must..genrally when protected or virtual functions are in picture and in edge cases space concerns ....I dont understand this point ?

having a composition object inside yourself, you can prevent derived classes from redefining your inherited virtual functions.

now edge case: think class with no data ( no non static data , no virtual functions, no virtual bases)such an empty class would have size more than 1 due to c++ technical issues...generally compiler inserts a char, depending on alignment etc you might see different size increase.
c++ decrees that free standing objects must have non zero size.
class holdsint { int x ; empty e } has size more than int

Empty base optimization class holdsint:private empty { int x } has size int....its generally viable under single inheritance only.

rules governing c++ object layout generally mean that the ebo cant be applied to derived classes that have more than one base

generally empty classes have typedefs enums static data non virts etc.....stl has a no of empty classes....e.g. unary_function and binary_function

private inheritance is most likely to be a legitimate design strategy when you are dealing with two classes not related by is a where one either needs a ccess to the protexted members of another or need to redefine one or more of its virtual functions.

things to remember:
private inheritance means is implemented in terms of . its usually inferior to composition but it makes sense when a derived class needs access to protected base class members or needs to redefine inherited virtual functions

uinlike composition privaet inheritance can enable the empty base optimization . this can be important for library developers who strive to minimize object sizes.

model has a or is implemented in terms of through composition

composition is also known as layering, containment, aggregation and embedding

their are two kinds of objects....objects in the real world and implementation artifacts ( buffers, mutexes, search trees)

things to remember:
composition has meanings completely different from that of public inheritance
in the application domain, composition means has a , in the implementation domain it means is implemented in terms of .

Never redefine a function's inherited default parameter value

Virtual functions are dynamically bound whereas default parameter values are statically bound

I wonder why compilers cannot check for this case themselves ?

How will this interact with the case where you don't know the number of arguments beforehand ..not sure even If that is an issue ?

You can use the nvi idiom, , public non  virtual specifies the default argument and then each private virtual can have its argument. Then it is clear and no redefinition happens in derived  Not sure what the author means here ?

Things to remember:
Never redefine an inherited parameter value, because default parameter values are statically bound, while virtual functions --the only functions you should be redefining -- are dynamically bound

Never define an inherited non virtual function

If mf is non virtual and Base and derived have their own version of this function then

D x;
B* pb = &x
D* pd = &x;
Pb->mf() & pd->mf() will call different functions.

References exhibit the same baffling behavior as pointers above. I don't really understand this ??

Things to remember:
Never redefine an inherited non virtual function

Sunday, June 24, 2007

consider alternatives to virtual functions

the template method pattern via the non virtual interface idiom
 write a public function that does the before work ( taking a lock, checking conditions) , calls a virtual fn to do the work and than does after work ( logging etc). generally that virtual fn is private ? why?
general design is clients call private virtual functions through public non virtual member functions- is known as the non virtual interface idiom.

non virtual function is like the virtual function wrapper.
note that derived classes redefine private virtual functions ? it says that is ok...but i am not convinced?
what if some library class has virtual and then we inherit and accidently override that function.
what if you just declare a virtual function without virtual in a derived class without he qualifier ??

the strategy pattern via function patterns
pass a function pointer with the defined type that is stored. and then call that function.

note that using the function pointer to calculate the health means that you need to weaken the encapsulation and provide either public accessors or make it a friend function.

strategy pattern via tr1::function pointer
why  health calculator shud be a function and not something that just acts like a function.

you can use the tr1::bind function to bind an argument to a function.

the classic strategy pattern

standard pattern.
to calculate health of a object , have a separate hierarchy of calculation functions, and keep an object of these calculation functions inside the object.

use the non virtual interface idiom. a form of the template method design pattern that wraps public non virtual member functions around less accessible virtual functions.

replace virtual functions with function pointer data members, a stripped down manifestation of the strategy design pattern

replace virtual functions with tr1::function data members thus allowing use of any callable entity with a signature compatible with what you need. this too is a form of the strategy design pattern

replace virtual functions in one hierarchy with virtual functions in another hierarchy. this is the conventional implementation of the strategy design pattern

things to remember:
alternative to virtual functions include the nvi idiom and various forms of the strategy desing pattern the nvi idiom is itself an example of the template design pattern

a disadvantage of moving functionality from a member function to a function outside the class is that the non member function lacks access to the class's non public members

tr1::function objects act like generalized function pointers, such object support all callable entities compatible with a given target signature

differnentiate between inheritance of interface and inheritance of implementation

the difference between these two is same as the difference between function declaration and function definition.

member function interfaces are always inherited.public inheritance means that trivially
the purpose of declaring a pure virtual function is to havea a dervied class inherit a function interface only.

you can provide a definition for a pure function also, but not a ver useful thing in general.

the purpose of declaring  simple virtual functions is to have derived classes inherit a function interface as well as a default implementation.

to avoid the chance of forgetting to define a proper version when a new class comes in, then you can define a function in the interface that is pure virtual and have it call a portected virtual function to do the actual thing.

that way every new class has to define the virtual function and it gets you
a non virtual member function specifies and invariant over specialization

pure virtual - interface only
simple virtual --interface and  default implementation
non virtual -- interface and a mandatory implementation

things to remember:
inheritance of interface is different from inheritance of implementation. under public inheritance derived calsses always inherit base class interfaces.
pure virtual functions specift inheritance of interface only
simple virtual functions specify inheritance of interface plus inheritance of a default implementation.
non virtual functions specift inheritance of interface plus inheritance of a mandatory implementation

avoid hiding inherited names

scope a derived class is nested inside its base class's scope

only names matter for determining what gets hidden
so if u define a fn in base and same name is defined in derived than that name will hide all the names in base.

if you want to carry over all names from base , use using base::name
is this behavior same for virtual functions also ? does their signature have to be exactly same ? check on this ?

if u want to enable only a few variants from the overload, than just have a forwarding function.
how do you do this if you want to bring in a variable definition in scope ?

things to remember:
names in derived classes hide names in base classes. under public inheritance this is never desirable.
to make hidden names visible again, eploy using declarations or forwarding functions

Umesh Kumar


make sure public inheritance models is a relationship

a derived class is a specialized version of base class so it should follow all constraints and provide all functionalities of the base class.

so pre conditions of dervied shud be subset of pre conditions of base
post conditions shud be superset of post conditions

differentiate between penguins cant fly and penguins can fly, but it is actually an error to make them fly.

things to remember:
public inheritance means is a . everything that applies to base classes must also apply to derived classes, because every derived class object is a base class objects

Thursday, June 21, 2007

Minimize compilation dependencies between files

In general a class specifies not just interface but a fair no of implementation details. Like private variables, inline functions etc.

Including standard headers is unlikely to be the problem as you can take advantage of precompiled headers.

You can use the pimpl idiom to get around with hiding the impl from the clients

I don't understand what is the meaning of replace dependencies on definitions with dependencies on declarations. ????
This minimizes compilation dependencies.

Two rules to follow:
Avoid using objects when object references and pointers will do
Depend on class declarations instead of class definitions whenever you can. ---I don't understand the note about moving dependencies to client's files at bottom of page 143 ???

Provide separate header files for declarations and definitions.

Look at iosfwd header file.???

Handle classes are classes that employ the pimpl idiom
They generally forward all their calls to the base class.

Or you can have an interface class exposed to client and actual class that implements the interface. Then you provide a static factory function that gives the actual class ( typically a shared pointer to it).

Obviously both of these approaches have the cost of most fn calls being virtual function calls.

Things to remember:
The general idea behind minimizing compilation dependencies is to depend on declarations instead of definitions. Two approaches based on this idea are handle classes and interface classes.

Library header files should exist in full and declaration only forms,. This applies regardless of whether templates are involved or not

Understand the ins and outs of inlining

Compilers are designed to optimize nicely over stretches of code without function calls.

Inlining can cause code bloat -> lower hit rates,memory crunch -> bad performance
Define function inside a class also makes it inline.
Inline functions should typically be in header files. Since inlining is generally a compile type thing
Compilers choose whether to inline or not
All but the trivial virtual fns are generally not inlined.
Most compilers have a diagnostic level that will result in a warning if compiler cant mark a function inline.
If your program takes the address of a function then the body of the function wud be generated even if compiler can imline it. Even if you don't do it ,sometimes compilers might just do that.

Compilers put hteir own code in constructors and destructors for handling exception, destruction In case of incomplete construction, calling base class constructor for derived classes etc.

If u have a inline function then clients are using it  means it is in there code, so u change implementation of that fn means clients have to recompile.

One pain in coding is that debuggers have trouble with inline functions

Things to remember:
Limit most inlinking to small frequently called functions. This facilititates debugging and binary upgradablity, minimizes potential code bloat, and mizimizes the changes of greater program speed.

Don't declare function templates inline just because they appeat in header files

Strive for exception safe code

When exceptions are thrown, foolowng should happen:

 Leak no resources ---use resource classes to manage all resources. Such classes also make code shorter.
Don't allow data structures to become corrupted---don't be left pointing to a deleted object,

Exception safe functions offer one of the following guarantees:
Basic guarantee --- exception thrown means program will remain in a valid state ( invariants satisfied etc)though exact state maybe unknown

Strong guarantee -- exception thrown means program state is unchanged. Calls to such functions are atomic…so boolean success or failure

NoThrow guarantee-- never throw exceptions. All operations on built in types are no throw.

Exception safe code always offers one of the three guarantees above. If not its not exception safe.

Int doSomething() throw() ---this doesn't mean no exc thrown, but that if a exception is thrown means serious error and call unexpected fun.

Try strongest guarantee but very hard.Strong guarantee is pretty hard because something could have changed state and you don't know what change it called

The general design strategy that you can use to get strong guarantee is copy , change copy  and swap in a non throwing oepration….obviously its costly and maynot give strong guarantee.

Normal : real obj = real obj { ptr to real data} --pimpl idiom

A functions exception safety guarantee is part of its interface….so give it as much weight as to other parts of its interface.

Things to remember:
Exception safe functions leak no resources and allow no data structures to become corrupted, even when exceptions are thjrown. Such functions offer the basic, strong on nothrow guarantees.

The strong guarantee can often be implemented via copy and swap, but the storng guarantee is not practical for all functions.

A function can usually offer a guarantee no stronger than the weakest guarantee of the functions it calls.

Tuesday, June 19, 2007

avoid returning handles to object internals

class rectangle {
Point& upperLeft() const { return pData->ulhc; }
Point& lowerRight() const { return pData->lrhc;}

will this compile ? isnt it wrong that this compiles ?

if a const member function returns a reference to data associated with an object that is stored outside the object itself, the caller of the function can modify that data....this a fallout of the limitations of bitwise constness.

reference pointers iterators are all handles and all have the same issue,

returning handle to objects internals always runs the risk of compromising encapsulation.

private fns are also object internals.

use const point& upperleft() cosnt { return pdata->ulhc; } solves the problem above.

returning handles can also lead to dangling handles. handles that refer to parts of objects that dont exist.... e.g. ( very similar to window example in previous item)

class guiobject{>>>}
const rectangle boundingBox (const guiobject& g);

guiobject * pgo;
const point* pupperleft = &( boundingbox(*pgo).upperleft());
a temp obj is former, upper kleft taken and then it gets destroyed.

so dont return object internal data ( their are notable exceptions like operator[] )

but it shud be an exception not a rule

things to remember:
avoid returning handles ( references , pointers, iterators) to object internals, not returning handles increases encapsulation helps const member functions act const and minimizes the creation of dangling handles.

Minimize casting

rules of c++ are designed to guarantee that type errors are impossible.

casting is more necessary and less dangerous in c and java than c++. approach it carefully in c++

old style casts: (T) expression , T(expression) ---both are exactly same

are these really same....i think second one invokes the defined conversion operator ...whereas first one just causes reinterpretation????

newer casts
const_cast( expression)

dynamic cast may have a significant runtime cost
reinterpret_cast means trouble, low level use only, results in unportable code

i dont understand why this should work ? ???
class widget {
explicit widget(int size);
dosomework( static_cast(15));

how does this work with that constructor is explicit ???

derived d ;
base* bp = &d;
bp and &d maynt be same ...in both single inheritance and virtual inheritance
this cant happen in c and java and c#.

can operators be virtual functions?

class window {
virtual void onResize() { ...}
class specialwindow:public window {
virtual void onResize(){
onresize doesnt call onresize on the base object. it makes a copy of the base object part and calls it on that object. use window::onResize for the effect.

cast creates a new temporary copy of the base class part.

if you find urself wanting to case its a sign that you could be approaching things the wrong way.

dynamic cast:
it can be quite slow.
one common implementation is based in part on string comparison of class names
s oa single 4 level hierarchy means upto 4 comparisons for each cast.

deeper or multiple inheritance hierarchies are more costly....its implemented this way to support dynamic linking
be afraid of dynamic cast in performance sensitive code.

you can maybe define a virtual function to avoid casts or have only single type of objects in a container to avoid it.

things to remember:
avoid casrs whenever practical, esp dynamic casts in performance sensitive code. if a design requires casting, try to develop a cast free alternative.

when casting is necessary try to hide it inside a function. clients can then call the function instead of putting casts in their own code

prefer c++ style casts to old style casts. they are easier to see and they are more specific about what they do.

postpone variable definition as long as possible

you dont want to incur the cost of variable creation and destruction if you are not going to use it completely.
dont ignore cost of creation if their are code paths where that variable wouldnt be used.

try to delay declaration till the time value is known.
then initialize and declare in the same statement, so that the cost of default construction of object is saved.

cost analysis in a loop:
widget w ;
for ( int i=0;i < n ; i++)
w =

for ( int i=0;i < n ; i++)
widget w

cost = 1 constructor + 1 destructor + n assignments
cost = n constructors + n destructors

pick whichever is better....note that second one is slightly more tight in that w isnt visible outside loop

things to remember:
postpone variable definitions as long as possible. It increases program clarity and improves program efficiency

Saturday, June 16, 2007

Consider support for a non throwing swap

so u can use the default implementation of swap. or you can provide a total specialization of a template to provide a more efficient version of swap.


the general idea is that the class provides a public swap function and then we provide a total specialization of the swap template of std namespace.


this is the trend in stl too, all containers ( vector, list etc) provide a public swap function and a total specialization of the general swap template.


c++ allows partial specialization of class templates but not partial specialization of function templates

template< class t>

swap <widget<t>> ( widget <t> & a , widget<t>&b) {..call fn defined in class).}


this doesnt compile

the way to get around this is you define the swap you want as before but in the namespace of your class ( assuming class is not in std namespace) then after that c++ name lookup rules will take care of picking the right implementation for you ( koenig rule ,argument dependent lookup)

 pimpl idiom is that you keep a pointer to implementation inside the object

make sure that your public member swap function shudnt throw an exception. i dont understand why ????

what is strong exception safety guarantee ???


from a client perspective if you are calling swap, then use a using declaration for general swap and make the actual call as swap (...) and not std::swap(...)

things to remember:

provide a swap member function, when std::swap would be inefficient for your type make sure your swap doesn't throw exceptions

if you offer a member swap also offer a non member swap that calls the member for classes ( not templates) specialize std::Swap too

when calling swap employ a using declaration for std::Swap then call without namespace qualification

its fine to totally specialize std templates for user defined types , but never try to add something completely new to std

Declare non member functions when type conversion should apply to all parameters

parameters are eligible for implicit type conversion only if they are listed in the parameter list of the function.


i am confused on this point, since i read a lot in strousstrup also on this and i don't remember what  all i read.


the opposite of a member function is a non member function not a friend function


read this funda there ?

things to remember:

if you need type conversions on all parameters to a function ( including the one that would otherwise  be pointed to by the this pointer) the function must be a non member function.

prefer non member non friend functions to member functions

if the function is just gathering functionality provided by other member functions which are actually interacting with class members etc... than you can consider making it a function in same namespace.


the more member functions or friend functions more code is possibly affected if you change the class implementation is changed.


this approach also reduces compilation issues since clients which use only one convenience function don't have to be recompiled on addition of another convenience function to namespace etc.


c++standard library is also organized the same way . their isnt a #include<c++standardlibrary> but #include <vector><lit> .....


partitioning functionality in this way is not possible when it comes from a class's member functions because a class must be defined in its entirety it cant be split into pieces

this also allows clients to add convenience functions if they want.

things to remember:

prefer non member non friend functions to member functions. doing so increases encapsulation, packaging flexibility and functional extensibility.

declare data members private

if everything in public interface is a function than clients don't have to think whether to put parenthesis or not when referring to api

encapsulation is the big reason ....if data members are private they can be replaced with computations/function calls/ different member  (say normal ptr by tr1 ptr) later on


this will let you notify other objects when data members are read or written and check port and pre conditions or other things if you want to.

practically encapsulated means unchangeable.....


protected data members are bad for similar reasons.

protected is no more encapsulated than public ..i don't understand this???

things to remember:

declare data members private. it gives clients syntactically uniform access to data members affords fine grained access control , allows invariant's to be enforced and offers class authors implementation flexibility.


protected is no more encapsulated than public

Test post from Windows Live Writer

To see if  things go correctly or not

don't try to return a reference when you must return an object

basically you might be returning reference to a object created locally in the function and that can cause all sorts of undefined behavior.

think if you really get a benefit from returning a reference to an object that you are creating in the function....also you need to worry who will free it. sometimes you mayn't even be able to get to freeing it.( think  w = a*b*c ) and operator  * returns a reference to a  object created on heap.....how do u get to temp created in a*b and the second temp created in temp*c

returning static objects is also awful....think multi threaded programs, think ( foo(i)*foo(j) == foo(k) * foo(l) )  will always return true ( because both side point to same static object)

static arrays are also a bad choice.

so if your function must return a new object than let that function return a new object, don't use reference or some other trick to try to get some performance benefit.

compilers can do lots of optimization to reduce/eliminate the overhead when it is possible.

so be sane.
things to remember:
never return a pointer or a reference to a local stack object. a reference to a heap allocated object or a pointer or reference to a local static object if there is a change that more than one such subject will be needed.

prefer pass by reference to const to pass by value

default is pass by value.fn parameters are initialized with copied of actual parameters.

passing params by refernce avoids the slicing problem.
when a derived class object is passed as a base class object, then the base class constructor is called,and derived class parts are lost.... that means virtual functions will resolve to base class inside called function ?

i want to test it out in code.

for built in types, stl iterators and types for which you know that pass by value is inexpensive , function object types you can use pass by value ( though you wanna be sure that the size of these types wont become large in future).

what are function object types and why is pass by value appropriate for them ?
things to remember:
prefer pass by reference to const over pass by value. its typically more efficient and it avoids the slicing problem

the rule doesn't apply to built in types and stl iterators and function object types for them pass by value is usually appropriate

Umesh Kumar


Treat class design as type design

Class designer = type designer.

How should objects fo your new type be created and destroyed ? --this effects your constructors, destructors, memory allocation and deallocation( operator new, new[], delete , delete[]) etc. Shud people call a static fn / normal creation/singleton/ restricted access (??) of some kind , who is responsible for releasing allocated resources, clients or class is self managing, centralized resource release, reference counting or auto ptr semantics when things are copied ?

How should object initialization differ from object assignment ? -- this answers the differences that will be there between your constructor and your assignment operators. think reference counting, no assignment, deep copy etc ??

What does it mean for objects of your new type to be passed by value  -- remember pass by value is defined by the implementation of your copy constructor.

What are the restrictions on legal values for your new type : --- this determines the invariants that your class needs to maintain, invariants determine your error checking and exceptions your functions throw and exception specifications of your functions

Does your new type fit into an inheritance graph ---if you are inheriting than you are constrained by your parent classes ( their virtual,abstract and non virtual functions and destructors) and if other classes are going to inherit from you than do you want to have virtual/abstract/non virtual functions and destructors ?

What kind of type conversion are allowed for your new type --- do you want to define any implicit conversion operators. And explicit conversion functions

What operators and functions make sense for the new type --- what functions you want to declare, shud they be member /friend/outside/ in same name space/public functions/private functions/ etc. Does it make sense to nest your class inside another class

What standard functions should be disallowed -- declare these private, e.g. may copy in network socket connection management class etc)

What is the undeclared interface of your new type ---what guarantees it offers w.r.t performance, exception safety, resource usage ( locks , dynamic memory), these impose restraints on your implementation.

How general is your new type : are you defining a new type or a whole new family of types, if you defined a family of types than you want to define a new class template not just a class

Is a new type really what you need ---- if purpose of new class is just old class + more functionality…then you can maybe use some non member functions or templates to get the work done

Its hard to design smart classes..but worth it.

Things to remember:
Class design is type design. Before defining a new type , be sure to consider all the issues discussed in this item

I need to reread this item and get a hang on it

Umesh Kumar


Make interfaces easy to use correctly and hard to use incorrectly

Type system is your primary ally in preventing undesirable code from compiling

Try that either it wont compile, or if it compiles it wont execute properly.

For e.g.
Date( int day , int month . Int year)

Date ( 3 , 40 , 2001);
Date( 30 , 3 , 2001);

Use type system:

Struct day { explicit(day) } ; struct month { explicit(month);} ; struct year(expli….}

Date ( day(23) , nmonth…..)

Be judicious it has become somewhat harder to write now.

To make sure you cant do Month(13)…we can

Have month as an enum type limited to 12, or
Class month{
Static month(jan()) { return month(1);

Private month(int m);

Another way to contrain things is as shown in item 4…make them const

Unless there is a good reason your types should behave consistently with built in types

Std::tr1_shared_ptr<investment> pinv( 0 , getridofinvestment) --wont compile because tr1 needs a explicit ptr, hence
Std::tr1_shared_ptr<investment> pinv (static_cast<investment*>(0), getridofinvestment() );

Tr1 avoids the cross dll problem ( what is cross dll problem ?) since by default it uses the version of delete defined in its dll

Things to remember:
Good interfaces are easy to use correctly and hard to use incorrectly. You should strive for these characteristics in all your interfaces

Ways to facilitate correctness use include consistenc in interfaces and behavioral compatiblity with built in types
Ways to prevent errors include creating new types , restricting oeprations on types, constraining object values and eliminating client resource management responsiblities

Tr1::shared_ptr supports custom deleters. This prevenets the cross dll problem , can be used  to automatically unlock mutexes etc.

Umesh Kumar


Thursday, June 14, 2007

store newed objects in smart pointers in standalone stmts

take an e.g.

int priority();
void processWidget( std::tr1::shared_ptr pw, int priority);

processWIdget( new widget() , priority() )
this wont compile because tr1 constructor in explicit

so how about

processwidget( std::Tr1:;shared_ptr( new widget) , priority());

this can cause a memory leak, say compiler decides to evaluate in this order:

new widget()
tr1::shared ptr ( widget)

if priority threw an exception then new widget wud be lost

the reason of this leak is that their is a lag between the time a resource is created and the time it is turned over to a resource managing object.
way out is simple:

std::tr1.sharedptr pw( new widget);
processwidget(pw , priority());

this works because compiler get less leeway in reordering operations across stmts that within them

things to remember:
store newed objects i nsmart pointers in standalone stmts. failure to do this can lead to subtle resource leaks when exceptions are thrown.

use the same form in corresponding uses of new and delete

match every new with the right delete.

new -> allocate memory + call constructor on that memory.
delete -> call destructor + deallocate memory

the big question for delete is how many objects reside in the memory being deleted . that determines how many destructor's wud be called.

memory layout for single objects is different from memory layout for arrays of objects.
fore.g. one way is
single objects : ob
array : n , obj , obj ...

compilers can implement in differently
dependign on the version of delete called it knows whether to delete an array or delete an object.

remember it when you have multiple constructors, in that case use consistently same new to allocate memory so that you know what version of delete to call in memory.

also be careful with typedef's as the author needs to define which delete shud be used with it.
typedef std::string addresslines[4];
std::string *pal = new AddressLines;

delete pal;
delete[] pal;

things to remember:
if you use [] in a new expression , you must use [] in the corresponding delete expression. if you dont use [] in a new expression , you mustnt use [] in the corresponding delete expression

provide access to raw resources in resource managing classes

you need direct access to raw resource for legacy or other reasons.

so you wanna provide implicit or explicit conversions to get to the raw resource.

tr1 and auto both offer a member function to perform explicit conversions ( interesting what wud happen if i were to take a copy of the raw pointer inside the auto _ptr...do i need to make sure that it wud never get deleted ?)

tr1 and auto also overload the -> and * operations to allow implicit conversion to the underlying raw pointers

you can give an operator to return the original datamember, so that compiler can automatically take the raw pointer when required based on acutal arguments. e.g.

class Font{
public: operator FontHandle() const { return f ; }
FontHandle f;

where font is a reosurce manager class for the FontHandle object

note it increases the chance of an error.

make interfaces easy to use correctly and hard to use incorrectly

raii classes dont exist for resource encapsulation purpose but to ensure that resources are released. so giving out the raw pointer from them isnt really against encapsulation.

tr1 hides the entire rcsp mechanism ..thus offering clients only what they need to see...so they kind of implement encapsulation of implementation too.

things to remember:
apis often require access to raw resource, so eahc raii class should offer a way to get at the resource it manages
access may be via explicit conversion or implicit conversion. in general explicit conversion is safer, but implicit conversion is more convenient for clients.

think carefully about copying behaviour in resource managing classes

for non heap based resources smart pointers like auto_ptr and tr1:;shread_ptr are generally inappropriate as resource handlers. you can just create your own resource managing classes for this purpose.

for e.g. mutex handler class, that acquires mutex while it is initializing in the constructor and releases the mutex in the destructor of the class.

now you need to worry about the copying behavior of this classes

general question we discuss is what happens when a raii class is copied. some options are :
prohibit copying: does it makes sense to allow copying of the object.( see item 6 on how to do it)

reference count the underlying source: if you want to hold on to a resource until the last object using it has been destroyed....similar copy meaning as in tr1..shared..in this case u can implement it using a data member of tr1..shared

talking of mutex for second case....tr1 will delete it by default ( though we want to release lock when reference count goes to zero)... hey you can specify a deleter function for tr1::shared_ptr....its not available for auto_ptr though

class lock {
explicit Lock(mutex* pm) : mutexPtr(pm, unlock) { lock(mutexptr.get() }
private :
std::tr1_shared_ptr mutexPtr;
note that unlock is the deleter function here

note that when count will go to zero the mutex wud automatically get deleted....lock destroyed->tr1 destructor -> unlock function

Third way out is : copy the underlying resource:
if having multiple copies is okay and you choose resource managing class so that any allocated resource is always freed ...u shud be a doing a deep copy.

fourth option is : transfer ownership of the underlying resource...like auto_ptrs.

things to remember:
copying an raii objects entails copying the resource it manages, so the copying behavior of the resource determines the copying behavior of the raii object

common raii class copying behaviors are disallowing copying and performing reference counting but other behaviors are possible.

Wednesday, June 13, 2007

use objects to manage resources

make sure that any resource allocated is always released ( think network connections, database connections, file handlers, lock, mutex, memory, other things)

mistakes are easy:
//createInvestment is a factory function that returns a investment object
int foo()
Investment * prt = createInvestment();
complex code that might return somehow ( think if /else/exception throw/code changed by someone/ some function that it called was "enhanced")

delete prt

so always use an object to manager resources.

STL auto_ptr is a good thing to use when resource is only used within a single block or function only.

int foo()
std::auto_ptr prt( createInvestment());

Two critical aspects:
Resource are acquired and immediately turned over to resource managing objects
resource managing objects use their destructors to make sure that resources are released ....since destructor wud be called when control leaves the block, so resources are automatically released. this can get tricky with exceptions being thrown in destructor's( something u shud never do..item 8)

coming back to auto_ptrs
auto_ptrs automatically delete whatever they were pointing to at the end
so when u copy a auto_ptr into another the first one looses its value, for e.g.

auto_ptr < inv..> * ptr(new...)
ptr2 = ptr1;
///ptr1 is null here

so you cant have auto_ptrs containers ( vector/list etc of auto_ptrs) since stl containers expect normal copying behavior

Another alternative to auto_ptrs is Reference counting smart pointer.
How does RCSP's differ from garbage collection -- cant break cycles of refererences

these can be used in stl containers

their is tr1:shared_ptr also which gives you RCSP behavior

Note that both tr1 and auto use delete in their implementation so so you cannt pass them arrays ( vector etc are good)

std::auto_ptr aps(new std::string[10]); this is bad since delete wud be called and not delte[] which is the right destructor to call.

So basically if you are releasing resources manually then you have done something wrong.

mostly auto or tr1 can help you out.

things to remember:
to prevent resource leaks, use RAII objects tha acquire resources in their constructors and release them in their destructors
two commonly useful RAII classes are tr1::shared_ptr and auto_ptr tr1::shared_ptr is usually the better choice , because its behavior when copied is intuitive., copying an auto_ptr sets it to null

Sunday, June 10, 2007

copy all parts of an object

copying functions = copy constructor, copy assignment

when you add any data member or something else, make sure that all the copying functions are properly modified for this.

in a good design only copy constructor and copy assignment are the only functiosn copying objects

make sure derived classes copy all the elements of their base class also.

why shud we not call one copying funtion from the other ?

things to remember:
copying functions should be sure to copy all of an objects data members and all of its base class parts

dont try to implement one of the copying functions in terms of the other. insread put common functionality in a third funtion that both call


handle assignments to self in operator =

self assignment is likely to happen for e.g.
a[i] = a[j]
*pt = *pg

or some other way it will happen.

in resource management classes be esp aware of releasing current resources and self assignment causing trouble. imagine
widget& widget::operator=(const widget& rhs_
delete pb;
pb = new Bitmap)*rhs.pb);

u can use if( this = &rhs) then return at top of function for this.

also the above is exception unsafe....pb will point to a deleted object if new Bitmap throws exception

so use combination of save elsewhere, copy new, delete elsewhere to avoid exception ....that makes it self assignment safe too

one thing is if someone else kept a ptr to this pb then self assignment has caused a complete copy to happen...also the new address is different from older address ( old pb[2] isnt same as new pb[2]) ....does this make sense ?

things to remember:
make sure operator= is well behaved when an object is assigned to itself techniques include comparing addresses of source and target objects, careful stmt ordering and copy and swap

make sure that any function operating on more than one object behaves correctly if two or more of the objects are the same,

item 10

have assignment operators return a reference to *this

in built in types...assignment returns a reference to its left hand operand....so you wanna follow the convention

it applies to all operators not just assignment

class widget {
widget& operator+=(const widget& rhs)
return *this);

widget& operator=(int rhs)
return *this ;


unless you have a good reason for doing things differently, dont.

things to remember:
have assignement operator a reference to *this

item 9

ver call virtual functions during construction or destruction

during base class construction virtual functions never go down into derived classes.

at what exact time does the derived class object come into existence ? at the momwnt the curly brace of constructor is entered ? or the moment the ) of arguments is seen ?

and similarly at what point is the derived object destructed ?

If you find that you need a virtual function call in the base class than you should have the dervied class pass the necessary info down to the base class and the non virtual function in base class can do the handling for you.

But make sure that thru no path of invocation, a virtual function is getting invoked till the constructor finishes ( or till some other point)? ( think insidiously...constructor calls non virtual function which calls a virtual function)...you need to make sure that this doesnt happen.

i think this is a big dilemma....if constructor cant call a virtual function then how do you provide extensiblity in the base class for things that need to be done during construction itself ?

things to remember:
dont call virtual functions during construction or destruction. because such calls will never go to a more dervied class than that of the currently executing constructor or destructor.

Saturday, June 9, 2007

item 8

prevent exceptions from leaving destructors.

not prohibited in c++, but dont throw them,

imagine a vector v having 10 elements and v[1] destructor ( on destruction of v) throws an exception.

if your destructor cant avoid having to throw an exception ( imagine destructor of a class providing db connections--resource managing classes) than code it to either terminate the program or just swallow the exception whichever is suitable. Swallowing is considered bas compared to termination.

things to remember:
destructors should never throw exceptions. if functions called in a destructor may throw, the destructor should catch any exceptions then tswallow them or terminate the program

if class clients need to be able to react to exceptions thrown during an operation the class should provide a refular ( i.e. no ndestructor) function that performs the operation

item 7

declare destructors virtual in polymorphic base classes

a factory function is a function that returns a base class pointer to a newly created derived class object.

to make sure that when a derived class object is deleted from a base class pointer than the entire object is deleted and not only the base class part of the object ( which is undefined....c++ doesnt define delete semantics when a base class destructor is called on a derived class object).

any class with virtual functions should almost certainly have a virtual constructor.

if a class doesnt have virtual fns than dont make the destructor virtual.

u can declare a pure virtual destructor to make a class abstract

things to remember:
plymorphic base classes should declare virtual destructors. if a class has virtual functions, it should have a virtual destructor.

classes not designd to be base classes or not designed to be used ploymorphically should not declare virtual destructors

Wednesday, June 6, 2007

C++ item 6

All compiler generated functions are public

To make sure that none can call a function foo() in your class.

Declare it as a private foo functions.

And don't define it.

Then even if friend or member functions were to invoke it then you will get a linker error.

A better way to get this linker error at compile time is :
Create a uncopyable class with cons , des, copy constructror et.c.

Now have general_class privately inherit from pupcopyabele class

Things to remember:

To disallow functionality automatically provided by compilers. Declare the corresponding member functions private and give no implementation. Using a base class like uncopyable is one wat to do this

Umesh Kumar


C++ item 5

An empty class isnt really empty.

A compilergenerates definition for these functions automatically.

Default constructor if u don't have a constructor

Copy constructor
Copy assignemtn

Class Empty {
        Empty() {}
Empty( const Empty& rhs) { }
~Empty() { }
Empty& operator=(const Empty& rhs) { }


These are generated only if needed, but are esily needed for .e.g
Empty e1
Empty e2(e1)
E2 = e1

Causes generation of all of them

What does it mean : compilers reject implicit copy assignment operators in derived classess that inherit from base classes declaring the copy assignment operator private. ?

Things to remember:

Compilers may implicitly generate a class's default constructor , copy constructor , copy assignment operator and destructor

Umesh Kumar


Sunday, June 3, 2007

Item 4

make sure the objects are initialized before they are used:

in general if you are in c part of c++ and initialization wud incur a runtime cost then it is not guaranteed to take place ( actual rules are complex).

always initialize your objects

differentiate between initialization and assignment.

for built in types their is no difference between initialization and assignment

the relative order of initialization of non local static objects defined in different translation units is undefined.

it is so because determining the correct order is unsolvably hard.

you can use static functions to get around this problem. but they are a problem in multithreaded functions.

what does it mean when you say " any kind of non const static object local or non local is trouble waiting to happen in the presence of multiple threads " ?

the easiest way around is to invoke them in proper order in the single threaded startup process.

things to remember:
manually initialise objects of built in type because c++ only sometimes initializes them itself.
in a constructor prefer use of the member initialization list to assignment inside the body of the constructor. list data members in the initialization list in the same order they are declared in the class.
avaoid initialization order problems across translation units be replacing non local static objects with local static objects.

Item 3

use const whenerver possible:

const allows you to specify a semantic constraint and compilers enforce it for you.

if the word const appears to the left of the asterisk what is pointed to is constant
if it is on left than the pointer itself is constant.

const widget* ptr = widget const * prt

having a function return a constant value often makes it possible to reduce the incidence of client errors without giving up the safety or efficiency

class Rational {...}
const Rational operator* (const Rational& a , const Rational & b);

this causes a compile error if clients were to say ?

Rational a ,b,cl
( a*b) = c ;

the above can be caused by a simple type in a comparison statement

one of the hallmarks of good user defined types is that they avoid gratuitous incompatiblities with the built ins.

const member functions make interface easier to understand as you know whether a given function can change the object or not.
They help efficiency as you can work with const& which are a way to improve efficiency in function calls taking uder objects as parameters.

functions differing only in their constness can be overloaded.e.g.

class TextBlock {
const char& operator[] ( std::size_t position) const { return text[position];}
char& operator[] ( std::size_t position) const { return text[position];}

private std::string text;

TextBlock tb;
std::cout << tb[0]; ---second function called

const TextBlock ctb;
std::cout << ctb[0]; ---first function called

note that we need to return references otherwise constness doesnt make sense. since the retunr value will get copied and const becomes useless.

will the below compile ?

class TextBlock {
const char operator[] ( std::size_t position) const { return text[position];}
char operator[] ( std::size_t position) const { return text[position];}

private std::string text;

constness = physical constness / logical constness

it says that this code compiles, whereas i think i have got an error when i tried to compile it in past:

class CTextBlock {
char& operator[](std::size_t position) const
{ return pText[position]; }
private char* pText;

mutable frees the non static data members from the constraints of bitwise constness

avoid code duplication in const and non const member functions:
see if you can call the const version from the non const version and cast away the constness ( dont do other way round....since the non const function change something in the object passed to it)

---also make sure you dont get yourself into an infinite loop non const calling itself again and again

things to remember:
declaring something const helps compiler detect usage errors. const can be applied to objects at any scope, to function parameters and return types and to member functions as a whole.
compilers enforce bitwise constness, but you should program using conceptual constness
when const and non const member functions have essentially identical implementations code duplications can be avoided by having the non const version call the const version

Item 2

prefer consts enums and inline to #define

strings are preferable to const char*

so const std::string author("scott meyers");

is preferable to
const char * const author = "scott meyers"

class gamePlayer
static const int numTurns = 5;
int scores[numTurns];

above is just a declaration for numTurns and not a definition.

c++ allows u to use after declaring only if its a static int and its address isnt taken.

if you take address of a class, then you have to define it also:

const int GamePlayer::numTurns;--- this goes in impl file not header file

in class initialization is allowed only for const ints.


const costEstimate
static const double fudgeFactor ;

const double constEstimate::fudgeFactor = 1.35;

how to get the value if you need it for compilation, as in the first class where you needed it to create the array: ( some compilers dont allow declaring value inside the class so you cannt use style of 1 )

class gamePlayer{
enum { numTurns = 5};
int scores[numTurns];


it is known as the enum hack.

it allows you to make sure people cannt get a reference to your constants.
it also makes sure compilers wont allocate any memory for it.

can people access that value or you can just declare a private enum ?

why wud the value not get picked up if it is cost Estimate style ?

try not to use macros at all. you can get all the efficiency of a macro with the type safety of a regular function by using templates for an inline functions.

#define call_with_max(a,b) f((a) >(b) ? (a) : (b) )

replace with

inline void callWithMax( const T&a , cons t T&b )
f ( a> b ? a:b);

preprocessor is bad but we need #include and #ifndef and #define
things to remember from this article:

for simple constants prefer const objects to enums to #defines
for function like macros prefer inline functions to #defines

Item 1

C++ has four dimensions :
c , object oriented c++ , template c++ , stl

the rules change when you move from one area to another so you need to know what changes and how.

to quote " c++ is not a unified language with a set of rules. it is a federation of four languages. C , object oriented c++ , template c++ , stl