Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C++ Don't Use Parent Class Constructor? [duplicate]

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 ?

like image 352
Emadpres Avatar asked Apr 06 '26 11:04

Emadpres


1 Answers

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.

like image 97
Baum mit Augen Avatar answered Apr 08 '26 23:04

Baum mit Augen