Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition)

Category: Programming
Author: Scott Meyers
All Hacker News 7
This Year Stack Overflow 3
This Month Stack Overflow 2


by anonymous   2019-07-21

Ok so you are learning C++ then learn the good practices from the start and avoid C++ pitfalls. Declaring and using C++ global objects that way can lead to very nasty behavior and long debugging sessions because you can't be sure the global object background which is declared at file global scope is initialized and properly constructed when you use it in another file. When you use such an object ,let's call it B, in another global object A in another file you cannot be sure B is initialized before the A and that leads to very nasty bugs or if you are lucky a crash. The solution then: make you object background a local static object i.e. local to a function like so:

TileMap& getBackground() {
  static TileMap background; //use of "camel case" for the class name
  return background; //return a reference to it 

That's it. Anywhere you want to use background just call getBackground(). The first time you call it, background local static will be initialized and good to use.

Some will say that this technique is related to the singleton design pattern but this is not my intent here it is just the proper way to use global objects if you absolutely need to. C++ is a great language especially with the release of C++11 but it has some pitfalls you need need to be aware of. Do yourself a favor: grab a copy of Effetive C++ it will teach almost everything you need to know to use the language properly

by andy.gurin   2019-07-21

The Konrad reply is OK, just a puntualization about the arrays.... There is a way to create an array of items(not pointers) and here it follows:

//allocate raw memory for our array
void *rawMemory = operator new[](30 * sizeof(Foo))

// point array_of_foos to this memory so we can use it as an array of Foo
Foo *array_of_foos = static_cast<Foo *>(rawMemory);

// and now we can create the array of objects(NOT pointers to the objects)
//  using the buffered new operator
for (int i = 0; i < 30; i++)

This approach is described here: http://www.amazon.com/gp/product/0321334876?ie=UTF8&tag=aristeia.com-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321334876

by anonymous   2019-07-21

Jonathan already resumed the differences between using namespace foo; and using foo::Bar; but I think his answer is unfortunately incomplete.

First: using namespace should never appear in a header file. By doing so you might render it impossible to use in combination with other header files because of a symbol clash...

Second: in general, you should try to limit the scope of the symbols as much as possible, you probably already do it while writing code:

for (size_t i = 0; i < 5; ++i)
  std::string myString = myVec.at(i);
  if (myString == "Foo") { std::cout << "Found"; break; }

Here it would be useless (and polluting) to have myString declared outside the for loop. In fact, that very advice can be found in a number of books:

From Scott Meyers' Effective C++, Item 26: Postpone variable definitions as long as possible.

From Herb Sutter and Andrei Alexandrescu's C++ Coding Standard, Item 18: Declare variables as locally as possible

There is no reason not to do the same with using declarations.

Third: consider alternatives to using: namespace aliasing and typedef.

// foo.h

class Foo

  std::vector<std::string> getSynonyms(const std::string& s) const;

  typedef std::map< std::string, std::vector<std::string> > synonyms_type;
  synonyms_type mSynonyms;

// foo.cpp (never in header, at general scope)

namespace fu = boost::fusion;

std::vector<std::string> Foo::getSynonyms(const std::string& s) const
  synonyms_type::const_iterator it =
    std::find(mSynonyms.begin(), mSynonyms.end(), s);

  std::vector<std::string> result;
  if (it != mSynonyms.end()) { result = it->second; }

  return result;

What are the advantages ?

  • namespace aliasing > reduce typing almost as much without injecting the types right in the current scope so without risk
  • typedef > reduce typing more than using and allow easy change of underlying type too.
by anonymous   2019-07-21

I had the same doubt as you until I came across this book by the C++ Guru Scott Meyers. Refer the third Item in this book where he talks in details about using const.

Just follow this advice

  1. If the word const appears to the left of the asterisk, what's pointed to is constant
  2. If the word const appears to the right of the asterisk, the pointer itself is constant
  3. If const appears on both sides, both are constant
by anonymous   2019-07-21

You should declare variables/instances of object as locally as possible. So, in this case, B would be the best option.

Consider that if you declare it at the top of your function body other people reading your code might wonder where you actually use the object. Therefore, by having the declaration close to where you actually use it will makes it easier to read.

There should not be any huge performance difference between case A and B.

There are some special cases such as allocating big chunks of memory or a thread pool for example. In these cases, since it might be time and ressources consumming you might need to find a better place to allocate them.

If you new to programming, you might want to consider reading Scott Meyers book, Effective C++. Item 26 talks about it : Postpone variable definitions as long as possible.

by krat0sprakhar   2018-10-11
I'm not sure how C++ for DL is different from regular C++ so take my advice with a grain of salt.

I took a class under Bjarne Stroustrup and he highly recommended Tour of C++ [0] as the best way to learn modern C++ for someone who already has some programming experience. That and of course, Effective C++[1] by Scott Meyers.

[0] - https://www.amazon.com/Tour-C-Depth/dp/0321958314

[1] - https://www.amazon.com/Effective-Specific-Improve-Programs-D...

by protomok   2017-08-20
Interesting article, love the emphasis on continual learning.

But I actually think we (software devs) need to focus more on mastering languages as opposed to learning many languages at a surface level.

Books like "Effective C++" (https://www.amazon.ca/Effective-Specific-Improve-Programs-De...) really showed me the huge divide between knowing a language and mastering a language.

by brg   2017-08-20
There are a number of programming books that I use to prepare for technical interviews. These are

1. Programming pearls, http://www.amazon.com/Programming-Pearls-2nd-Jon-Bentley/dp/...

2. Effective C++, http://www.amazon.com/Effective-Specific-Improve-Programs-De...

3. Programming Problems, http://www.amazon.com/Programming-Problems-Primer-Technical-...

The reason for these texts is not because they are overtly insightful or well written, it is because they have a large number of problems with completely coded solutions. After working through these basics, programming interviews are much more enjoyable.

by mathias_10gen   2017-08-20
I think Effective C++ by Scott Meyers[1] is the gold standard when it comes to books on writing good clean C++. It assumes that you already know the basic syntax though and already know how to program. This allow him to skip the intro stuff that take up the most space in many books and get strait to telling you what you need to know to write better code.

[1] http://www.amazon.com/Effective-Specific-Improve-Programs-De... (Make sure you get the latest edition, a lot has changed for the better)

by Aaron   2017-08-20

Problem Summary

There are two competing concerns in this question.

  1. Life-cycle management of Subsystems, allowing their removal at the right time.
  2. Clients of Subsystems need to know that the Subsystem they are using is valid.

Handling #1

System owns the Subsystems and should manage their life-cycle with it's own scope. Using shared_ptrs for this is particularly useful as it simplifies destruction, but you should not be handing them out because then you loose the determinism you are seeking with regard to their deallocation.

Handling #2

This is the more intersting concern to address. Describing the problem in more detail, you need clients to receive an object which behaves like a Subsystem while that Subsystem (and it's parent System) exists, but behaves appropriately after a Subsystem is destroyed.

This is easily solved by a combination of the Proxy Pattern, the State Pattern and the Null Object Pattern. While this may seem to be a bit complex of a solution, 'There is a simplicity only to be had on the other side of complexity.' As Library/API developers, we must go the extra mile to make our systems robust. Further, we want our systems to behave intuitively as a user expects, and to decay gracefully when they attempt to misuse them. There are many solutions to this problem, however, this one should get you to that all important point where, as you and Scott Meyers say, it is "easy to use correctly and hard to use incorrectly.'

Now, I am assuming that in reality, System deals in some base class of Subsystems, from which you derive various different Subsystems. I've introduced it below as SubsystemBase. You need to introduce a Proxy object, SubsystemProxy below, which implements the interface of SubsystemBase by forwarding requests to the object it is proxying. (In this sense, it is very much like a special purpose application of the Decorator Pattern.) Each Subsystem creates one of these objects, which it holds via a shared_ptr, and returns when requested via GetProxy(), which is called by the parent System object when GetSubsystem() is called.

When a System goes out of scope, each of it's Subsystem objects gets destructed. In their destructor, they call mProxy->Nullify(), which causes their Proxy objects to change their State. They do this by changing to point to a Null Object, which implements the SubsystemBase interface, but does so by doing nothing.

Using the State Pattern here has allowed the client application to be completely oblivious to whether or not a particular Subsystem exists. Moreover, it does not need to check pointers or keep around instances that should have been destroyed.

The Proxy Pattern allows the client to be dependent on a light weight object that completely wraps up the details of the API's inner workings, and maintains a constant, uniform interface.

The Null Object Pattern allows the Proxy to function after the original Subsystem has been removed.

Sample Code

I had placed a rough pseudo-code quality example here, but I wasn't satisfied with it. I've rewritten it to be a precise, compiling (I used g++) example of what I have described above. To get it to work, I had to introduce a few other classes, but their uses should be clear from their names. I employed the Singleton Pattern for the NullSubsystem class, as it makes sense that you wouldn't need more than one. ProxyableSubsystemBase completely abstracts the Proxying behavior away from the Subsystem, allowing it to be ignorant of this behavior. Here is the UML Diagram of the classes:

UML Diagram of Subsystem and System Hierarchy

Example Code:

#include <iostream>
#include <string>
#include <vector>

#include <boost/shared_ptr.hpp>

// Forward Declarations to allow friending
class System;
class ProxyableSubsystemBase;

// Base defining the interface for Subsystems
class SubsystemBase
    // pure virtual functions
    virtual void DoSomething(void) = 0;
    virtual int GetSize(void) = 0;

    virtual ~SubsystemBase() {} // virtual destructor for base class

// Null Object Pattern: an object which implements the interface to do nothing.
class NullSubsystem : public SubsystemBase
    // implements pure virtual functions from SubsystemBase to do nothing.
    void DoSomething(void) { }
    int GetSize(void) { return -1; }

    // Singleton Pattern: We only ever need one NullSubsystem, so we'll enforce that
    static NullSubsystem *instance()
      static NullSubsystem singletonInstance;
      return &singletonInstance;

    NullSubsystem() {}  // private constructor to inforce Singleton Pattern

// Proxy Pattern: An object that takes the place of another to provide better
//   control over the uses of that object
class SubsystemProxy : public SubsystemBase
  friend class ProxyableSubsystemBase;

    SubsystemProxy(SubsystemBase *ProxiedSubsystem)
      : mProxied(ProxiedSubsystem)

    // implements pure virtual functions from SubsystemBase to forward to mProxied
    void DoSomething(void) { mProxied->DoSomething(); }
    int  GetSize(void) { return mProxied->GetSize(); }

    // State Pattern: the initial state of the SubsystemProxy is to point to a
    //  valid SubsytemBase, which is passed into the constructor.  Calling Nullify()
    //  causes a change in the internal state to point to a NullSubsystem, which allows
    //  the proxy to still perform correctly, despite the Subsystem going out of scope.
    void Nullify()

      SubsystemBase *mProxied;

// A Base for real Subsystems to add the Proxying behavior
class ProxyableSubsystemBase : public SubsystemBase
  friend class System;  // Allow system to call our GetProxy() method.

      : mProxy(new SubsystemProxy(this)) // create our proxy object
      mProxy->Nullify(); // inform our proxy object we are going away

    boost::shared_ptr<SubsystemProxy> GetProxy() { return mProxy; }

    boost::shared_ptr<SubsystemProxy> mProxy;

// the managing system
class System
    typedef boost::shared_ptr< SubsystemProxy > SubsystemHandle;
    typedef boost::shared_ptr< ProxyableSubsystemBase > SubsystemPtr;

    SubsystemHandle GetSubsystem( unsigned int index )
        assert( index < mSubsystems.size() );
        return mSubsystems[ index ]->GetProxy();

    void LogMessage( const std::string& message )
        std::cout << "  <System>: " << message << std::endl;

    int AddSubsystem( ProxyableSubsystemBase *pSubsystem )
      LogMessage("Adding Subsystem:");
      return mSubsystems.size()-1;

      LogMessage("System is constructing.");

      LogMessage("System is going out of scope.");

    // have to hold base pointers
    typedef std::vector< boost::shared_ptr<ProxyableSubsystemBase> > SubsystemList;
    SubsystemList mSubsystems;

// the actual Subsystem
class Subsystem : public ProxyableSubsystemBase
    Subsystem( System* pParentSystem, const std::string ID )
      : mParentSystem( pParentSystem )
      , mID(ID)
         mParentSystem->LogMessage( "Creating... "+mID );

         mParentSystem->LogMessage( "Destroying... "+mID );

    // implements pure virtual functions from SubsystemBase
    void DoSomething(void) { mParentSystem->LogMessage( mID + " is DoingSomething (tm)."); }
    int GetSize(void) { return sizeof(Subsystem); }

    System * mParentSystem; // raw pointer to avoid cycles - can also use weak_ptrs
    std::string mID;

// Actual Use Example
int main(int argc, char* argv[])

  std::cout << "main(): Creating Handles H1 and H2 for Subsystems. " << std::endl;
  System::SubsystemHandle H1;
  System::SubsystemHandle H2;

  std::cout << "-------------------------------------------" << std::endl;
    std::cout << "  main(): Begin scope for System." << std::endl;
    System mySystem;
    int FrankIndex = mySystem.AddSubsystem(new Subsystem(&mySystem, "Frank"));
    int ErnestIndex = mySystem.AddSubsystem(new Subsystem(&mySystem, "Ernest"));

    std::cout << "  main(): Assigning Subsystems to H1 and H2." << std::endl;

    std::cout << "  main(): Doing something on H1 and H2." << std::endl;
    std::cout << "  main(): Leaving scope for System." << std::endl;
  std::cout << "-------------------------------------------" << std::endl;
  std::cout << "main(): Doing something on H1 and H2. (outside System Scope.) " << std::endl;
  std::cout << "main(): No errors from using handles to out of scope Subsystems because of Proxy to Null Object." << std::endl;

  return 0;

Output from the code:

main(): Creating Handles H1 and H2 for Subsystems.
  main(): Begin scope for System.
  <System>: System is constructing.
  <System>: Creating... Frank
  <System>: Adding Subsystem:
  <System>: Creating... Ernest
  <System>: Adding Subsystem:
  main(): Assigning Subsystems to H1 and H2.
  main(): Doing something on H1 and H2.
  <System>: Frank is DoingSomething (tm).
  <System>: Ernest is DoingSomething (tm).
  main(): Leaving scope for System.
  <System>: System is going out of scope.
  <System>: Destroying... Frank
  <System>: Destroying... Ernest
main(): Doing something on H1 and H2. (outside System Scope.)
main(): No errors from using handles to out of scope Subsystems because of Proxy to Null Object.

Other Thoughts:

  • An interesting article I read in one of the Game Programming Gems books talks about using Null Objects for debugging and development. They were specifically talking about using Null Graphics Models and Textures, such as a checkerboard texture to make missing models really stand out. The same could be applied here by changing out the NullSubsystem for a ReportingSubsystem which would log the call and possibly the callstack whenever it is accessed. This would allow you or your library's clients to track down where they are depending on something that has gone out of scope, but without the need to cause a crash.

  • I mentioned in a comment @Arkadiy that the circular dependency he brought up between System and Subsystem is a bit unpleasant. It can easily be remedied by having System derive from an interface on which Subsystem depends, an application of Robert C Martin's Dependency Inversion Principle. Better still would be to isolate the functionality that Subsystems need from their parent, write an interface for that, then hold onto an implementor of that interface in System and pass it to the Subsystems, which would hold it via a shared_ptr. For example, you might have LoggerInterface, which your Subsystem uses to write to the log, then you could derive CoutLogger or FileLogger from it, and keep an instance of such in System.
    Eliminating the Circular Dependency

by litb   2017-08-20


Introductory, no previous programming experience

Introductory, with previous programming experience

* Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

Best practices



Reference Style - All Levels

C++11/14 References:

  • The C++ Standard (INCITS/ISO/IEC 14882-2011) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. As usual, the first release was quite expensive ($300+ US), but it has now been released in electronic form for $60US.

  • The C++14 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++17.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++1y/C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.

Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

by anonymous   2017-08-20

The thing to keep in mind here is templates are different from language features like generics in languages like C#.

It is a fairly safe simplification to think of templates as an advanced preprocessor that is type aware. This is the idea behind Template metaprogramming (TMP) which is basically compile time programming.

Much like the preprocessor templates are expanded and the result goes through all of the same optimization stages as your normal logic.

Here is an example of rewritting your logic in a style more consistent with TMP. This uses function specialization.

template<bool X>
double foo(double x);

double foo<true>(double x)
    return moo(x);

double foo<false>(double x)
    return bar(x);

TMP was actually discovered as a happy accident and is pretty much the bread and butter of the STL and Boost.

It is turing complete so you can do all sorts of computation at compile time.

It is lazily evaluated so you could implement your own compile time asserts by putting invalid logic in a specialization of a template that you don't want to be used. For example if I were to comment out the foo<false> specialization and tried to use it like foo<false>(1.0); the compiler would complain, although it would be perfectly happy with foo<true>(1.0);.

Here is another Stack Overflow post that demonstrates this.

Further reading if interested:

  1. Modern C++ Design
  2. C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond
  3. Effective C++
by anonymous   2017-08-20

I think this statement reflects the confusion here (emphasis mine):

I do not understand what specifically is required in a class to be eligible for being a base clas (not a polymorphic one)?

In idiomatic C++, there are two uses for deriving from a class:

  • private inheritance, used for mixins and aspect oriented programming using templates.
  • public inheritance, used for polymorphic situations only. EDIT: Okay, I guess this could be used in a few mixin scenarios too -- such as boost::iterator_facade -- which show up when the CRTP is in use.

There is absolutely no reason to publicly derive a class in C++ if you're not trying to do something polymorphic. The language comes with free functions as a standard feature of the language, and free functions are what you should be using here.

Think of it this way -- do you really want to force clients of your code to convert to using some proprietary string class simply because you want to tack on a few methods? Because unlike in Java or C# (or most similar object oriented languages), when you derive a class in C++ most users of the base class need to know about that kind of a change. In Java/C#, classes are usually accessed through references, which are similar to C++'s pointers. Therefore, there's a level of indirection involved which decouples the clients of your class, allowing you to substitute a derived class without other clients knowing.

However, in C++, classes are value types -- unlike in most other OO languages. The easiest way to see this is what's known as the slicing problem. Basically, consider:

int StringToNumber(std::string copyMeByValue)
    std::istringstream converter(copyMeByValue);
    int result;
    if (converter >> result)
        return result;
    throw std::logic_error("That is not a number.");

If you pass your own string to this method, the copy constructor for std::string will be called to make a copy, not the copy constructor for your derived object -- no matter what child class of std::string is passed. This can lead to inconsistency between your methods and anything attached to the string. The function StringToNumber cannot simply take whatever your derived object is and copy that, simply because your derived object probably has a different size than a std::string -- but this function was compiled to reserve only the space for a std::string in automatic storage. In Java and C# this is not a problem because the only thing like automatic storage involved are reference types, and the references are always the same size. Not so in C++.

Long story short -- don't use inheritance to tack on methods in C++. That's not idiomatic and results in problems with the language. Use non-friend, non-member functions where possible, followed by composition. Don't use inheritance unless you're template metaprogramming or want polymorphic behavior. For more information, see Scott Meyers' Effective C++ Item 23: Prefer non-member non-friend functions to member functions.

EDIT: Here's a more complete example showing the slicing problem. You can see it's output on codepad.org

#include <ostream>
#include <iomanip>

struct Base
    int aMemberForASize;
    Base() { std::cout << "Constructing a base." << std::endl; }
    Base(const Base&) { std::cout << "Copying a base." << std::endl; }
    ~Base() { std::cout << "Destroying a base." << std::endl; }

struct Derived : public Base
    int aMemberThatMakesMeBiggerThanBase;
    Derived() { std::cout << "Constructing a derived." << std::endl; }
    Derived(const Derived&) : Base() { std::cout << "Copying a derived." << std::endl; }
    ~Derived() { std::cout << "Destroying a derived." << std::endl; }

int SomeThirdPartyMethod(Base /* SomeBase */)
    return 42;

int main()
    Derived derivedObject;
        //Scope to show the copy behavior of copying a derived.
        Derived aCopy(derivedObject);
by anonymous   2017-08-20

After a brief look at SeqAn manual I came up with the following example:

namespace Tags {
struct Noone {};
struct Someone {};

template <typename T, typename U>
class Base {
  using KindOfThing = U;

  // implement algorithm
  bool knock() {
    return static_cast<T*>(this)->knockKnock();

template <typename T>
class Base<T, Tags::Noone> {
  using KindOfThing = Tags::Noone;

  void work() {

class WashingMachine : public Base<WashingMachine, Tags::Noone> {
  void makeSounds(){};

  void doJob(){};

class Meow : public Base<Meow, Tags::Someone> {
  Meow() : meows(0) {}

  //implement Base interface
  void listen() { std::cout << "..." << std::endl; }

  //implement Base interface
  bool knockKnock() {
    std::cout << "Meow..." << std::endl;
    return meows++ > 3;

  void tellName(std::string const& name) { (void)name; }

  int meows;

class WhoIsThere : public Base<WhoIsThere, Tags::Someone> {
  //implement Base interface
  void listen() { std::cout << "<Steps>..." << std::endl; }

  //implement Base interface
  bool knockKnock() {
    std::cout << "WhoIsThere?" << std::endl;
    return isDone;

  void tellName(std::string const& name) {
    isDone = true;
    std::cout << name + " is here))!" << std::endl;

  bool isDone;

template <typename T, typename U>
void performKnocking(T&& item, U) {
  std::cout << "......" << std::endl;
  while (!item.knock())

template <typename T>
void performKnocking(T&& item, Tags::Noone) {
  std::cout << "Noone" << std::endl;

template <typename... TArgs>
void performKnockingToEveryone(TArgs&&... sequence) {
  int dummy[] = {(performKnocking(sequence, typename TArgs::KindOfThing()), 0)...};

int main() {
    Meow(), WashingMachine(), WhoIsThere(), Meow(), WashingMachine());
  return 0;

The point is that the design that SeqAn is telling is moving from the realm of usual OOP programming (with polymorphism, type abstractions and etc.) to C++ template programming (more precisely see Item 1 in Effective C++). The same like there are zellions of books on OOP design, not less, if not more, there are material on Template C++ programming (see The Definitive C++ Book Guide and List for both kinds of programming techniques and more).

In this example, I show two techniques of designing that the SeqAn documentation emphasizes.

  • There is a base implementing some kind of operation that has several steps common for other subclasses. The base provide kind of Template Method (there is nothing related to C++ templates there, it is purely OOP pattern, just the name has the same word) from operations - setting an interface (not OOP interface, but C++ Template interface) for the deriving classes. Those subclasses, in their turn, implement those operations. You get static (resolved at compile time behaviour) polymorphism (type that has an interface that has different behavior from one instance to another). There is no runtime polymorphism because for runtime (OOP realm) those all are different types, they are all different for compile time as well. This polymorphism exists in C++ templates (templates parameters and templates declarations). Example: Boost Iterator Facade.

  • Tag dispatching technique employs function overloading resolution depending on the argument(s) type(s). It helps when you have free function as part of your API and chose necessary one to call depending on situation (example STL Iterators iterator_tag(s) and iterator free functions). For exmaple, consider OOP Visitor Pattern and you have AbstractVisitor and KnockingVisitor. You take a vector of Base* and call accept on each, that calls visit and your KnockingVisitor does the knocking. With tag dispatching you use tags. This might be a lame comparation between OOP techniques and tag dispatching, but it is just one of many possible examples. Like with OOP design where and what pattern to use, with C++ Templates techniques you need experience.

This example is quite primitive, because there is no actual task behind it is design, however, when you have an ambitious goal that gets more interesting and complicated. C++ Templates might be one of the choices to archive it.

by anonymous   2017-08-20

You should take a look at the book "Effective C++", especially Chapter 2. http://www.amazon.com/Effective-Specific-Improve-Programs-Designs/dp/0321334876

Chapter 2: Constructors, Destructors, and Assignment Operators

by anonymous   2017-08-20

The guide to the language by Stroustrup:

Scott Meyers's triple are quite useful: Effective C++, More Effective C++, and Effective STL.

Also see these questions:
- https://stackoverflow.com/questions/155762/best-c-resource
- Java FAQ equivalent of C++ FAQ lite?
- C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]
- What C++ pitfalls should I avoid?
- New to C++. Question about constant pointers