I wondering why in c++ can't use parent class constructor for an specific signature, in case that derived class miss that?
For example in below sample, I can't initialize dd object with std::string.
#include <iostream>
class Base
{
int num;
std::string s;
public:
Base(int _num){ num = _num;}
Base(std::string _s){ s = _s;}
};
class Derived : public Base {
public:
Derived(int _num):Base(_num){}
};
int main()
{
Base b(50);
Derived d(50);
Base bb("hell");
Derived dd("hell"); // <<== Error
return 0;
}
With Inheritance I expect to extend a class and not losing previous functionality but here I feel losing some.
In a more practical example, I create my version of std::string but It doesn't behave like a std::string in some cases :
#include <string>
#include <iostream>
class MyString: public std::string {
public:
void NewFeature(){/* new feature implementation*/}
};
int main()
{
MyString s("initialization"); // <<== Error: I expect to initialize with "..."
cout<<s; // <<== Error: I expect to print it like this.
return 0;
}
Can somebody give some explanation ?
2 Answers 2
If you want to inherit the constructors too, you need to tell the compiler in your code:
class Derived : public Base {
public:
using Base::Base; // <- Makes Base's constructors visible in Derived
};
As for "Why do I need to do this?": The cheap answer is: Because the standard says so.
Why it does that is speculation (if you do not ask the committee members themselves). Most likely they wanted to avoid "surprising" or "un-intuitive" code-behavior.
6 Comments
using std::string::std::string doesn't work, I need the why of this problem. why Inheritance smells here .std::string. (Pretty much what I wrote in the answer. :) )using std::string::string work (recall that std::string is actually a typedef for a particular specialization of std::basic_string...)cout<<s;. I should do some another work to make it work and so on ?I don't have enough rep to flag as duplicate, but Inheriting constructors answers this sufficiently.
Basically, pre-C++11 it was in the standard to not allow constructor inheritance. C++11 has changed this and you can now inherit constructors.
Comments
Explore related questions
See similar questions with these tags.