Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we "inherit" constructors in C++ ? What's is exact definition of "inheriting"

I wonder why people say:

"Inheriting class doesn't inherit the constructor".

If you could CAN use the parent class' constructor, and the parameterless constructor are called automatically no matter what.

Example:

#include <iostream>
using namespace std;

class A {
    private :
        int x;
    public  :
        A () {
            cout << "I anyway use parameter-less constructors, they are called always" << endl;
        }
        A (const int& x) {
            this->x = x;
            cout << "I can use the parent constructor" << endl;
        }
};

class B : public A {
    private :
        int y;
    public  :
        B() {

        }
        B (const int& x, const int& y) : A (x) {
            this->y = y;
        }
};

int main() {

    B* b  = new B(1,2);
    B* b1 = new B();
    return 0;
}

http://ideone.com/e.js/6jzkiP

So is it correct to 'say', constructors are inherited in c++ ? What is exact definition of "inherit" in programming languages ?

Thanks in advance.

like image 986
Paul Brewczynski Avatar asked Nov 17 '13 11:11

Paul Brewczynski


3 Answers

I wonder why people say: "Inheriting class doesn't inherit the constructor".

Perhaps it is best to illustrate this with an example:

struct Foo
{
  Foo(int, int) {}
};

struct Bar : Foo
{
};

What it means is that there is no Bar::Bar(int, int) constructor that you can call, despite the existence of a constructor with the same parameter list in the base class. So you cannot do this:

Bar b(42, 42);

In C++11, you can actually inherit constructors, but you must be explicit about it:

struct Bar : Foo
{
  using Foo::Foo;
};

Now, you can say Bar b(42, 42);

like image 126
juanchopanza Avatar answered Nov 08 '22 08:11

juanchopanza


What they mean is that constructor signatures are not inherited.

In your example, B does not have a constructor taking a single const int& even though its base class does. In this sense it has not "inherited" the constructor (but can still make use of it).

like image 5
NPE Avatar answered Nov 08 '22 07:11

NPE


I think what they mean is:

struct A {
    A(int, int) { }
};

struct B : public A {
};

int main()
{
    A a(1, 2); // ok
    B b(1, 2); // error
}

To compare with “non-special” member functions:

struct A {
    void f() { }
};

struct B : public A {
};

int main()
{
    A a;
    B b;
    a.f(); // ok
    b.f(); // ok too
}

But of course, from within B you can call accessible A constructors (as automatically generated ones do). Ditto for the destructor.


Note that in C++11 you can use the “inheriting constructors” feature:

struct A {
    A(int, int) { }
};

struct B : public A {
    using A::A;
};

int main()
{
    A a(1, 2); // ok
    B b(1, 2); // ok now
}
like image 3
gx_ Avatar answered Nov 08 '22 08:11

gx_