How to inherit constructors

I've been through the internet and back, trying to looks for forum posts or tutorials on how to inherit a constructor from a parent class to a child class. I understand that when inheriting, constructors don't automatically inherit. How do I make it so that they do? I've been trying to experiment, but I'm not sure if the constructor is actually inheriting when I do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//IN PARENT.H
      class Parent
      {
      protected:
            int health, xp, atkPow;
      public:
	Base(int a, int b, int c);
      };


      //IN PARENT.CCP
      Parent::Parent(int a, int b, int c)
      {
            health = a;
            xp = b;
            atkPow = c;
      }


1
2
3
4
5
6
7
8
9
10
11
12
13
14
//IN CHILD.H
      class Child : public Parent
      {
      public:
            Child(int a, int b, int c);      
      };

      
      //IN CHILD.CPP
      //Is the following line the correct way to inherit a constructor?
      Child::Child(int a, int b, int c) : Base(a, b, c)
      {
            //Are the contents of the parent constructor copied here?
      }


If that is not the correct way to inherit a constructor, could you please teach me the right way to do so, or lead me to an informative tutorial on how to do so?

Thanks in advance.
You are delegating work to a parent constructor here. To inherit constructor you should do:
1
2
3
4
class Child : public Parent
{
    using Parent::Parent;
};
http://coliru.stacked-crooked.com/

(Also you forgot to rename Base to Parent)
Last edited on
Hi,

There are a bunch of things that come up if you google "C++ inherit constructors"

Note you need to enable C++11 on your compiler.


http://codexpert.ro/blog/2013/08/26/inherited-constructors-in-cpp11/
http://stackoverflow.com/questions/347358/inheriting-constructors
(Also you forgot to rename Base to Parent)

Noted

using Parent::Parent;

I'm not familiar with the using keyword. Should I look into it, or is it safe to say that the constructor is basically copied at this point?
Using keyword has several meanings depending on context. What you need: http://en.cppreference.com/w/cpp/language/using_declaration
(In class definition, paragraph 2)

All meanings of using: http://en.cppreference.com/w/cpp/keyword/using
Topic archived. No new replies allowed.