How to pass a default parameter for std::shared_ptr<PureVirtualClass>

Eric Abramov picture Eric Abramov · Dec 29, 2016 · Viewed 6.9k times · Source

I have a function of type

virtual void foo(bla, bla, bla, std::shared_ptr<LoggerInterface> logger) = 0;

And I want to pass a default parameter with NULL pointer, something like:

virtual void foo(bla, bla, bla, std::shared_ptr<LoggerInterface> logger = NULL) = 0;

So that in implementation, if logger is NULL I do nothing with it, otherwise I use the logger.

I've tried to look for a solution but cannot find..

UPD: Duplicate claim is irrelevant, I am asking about default NULL parameter.

Is it possible that gcc 4.4 doesn't support nullptr?

Answer

skypjack picture skypjack · Dec 30, 2016

You can simply do this:

virtual void foo(bla, bla, bla, std::shared_ptr<LoggerInterface> logger = {}) = 0;

As you can see here, both the empty constructor and nullptr give the same result, that is:

Constructs a shared_ptr with no managed object, i.e. empty shared_ptr