Sesquipedalian
Sesquipedalian

Reputation: 257

How can I share a common default parameter value between base and derived class in C++?

Consider the following classes:

class A {
   public:
   A( std::string param = "123" ) {} 
};

class B : public A{ 
   public: 
   B() : A() {}
   B( std::string param ) : A( param ) {}
};

Is there a better way than this to make sure the default parameter value from A is used? I want someone to be able to construct B either by providing a string param or not.

Upvotes: 2

Views: 105

Answers (1)

Depending on what you exactly want, that might be the best option (if you want to ensure that a change in the default parameter in the base is immediately picked up in the derived type), or else you can use the same approach as you did in the base:

class B : public A {
public:
   B(std::string const & arg = "123") : A(arg) {}
// ...

In this case, you need to remember to update the default value in the derived type if you change the value in the base type. You could also factor that out to a constant:

const char* defaultParam = "123";
class A {
public:
   A(std::string const& s=defaultParam) // ...
//...
};
class B : public A {
public:
   B(std::string const& s=defaultParam) : A(s) {}
//...

Upvotes: 2

Related Questions