Calling constructor of parent class by calling constructor

Hi,

I've got a question about constructors and calling their parent constructors by the way:
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
  class parent
  {
    public:
      parent();
      parent(int a);
  };

  class child : public parent
  {
    public:
      child();
      child(int a, int b);
  };


As far as I know, when I create an object of type child now, I have two ways:
1. calling a constructor of child that has exactly the same arguments like it's parent constructor:
1
2
3
4
5
6
child test();

child::child()
{
  // do something
}

2. calling a constructor of child with specific arguments other than it's parent constructor, but in this case I have to call the parent constructor manually:
1
2
3
4
5
6
child test(5, 10);

child::child(int a, int b) : parent()    // alternatively parent(int)
{
  // do something
}

Am I wrong or does it work like this?

If yes, why is it possible for me to create own classes which inherit big classes (my example was about Qt, there I defined a class my_window : public QWidgets) and create an instance of them by calling a self defined constructor with other and unique arguments without calling the parent constructor (QWidget::QWidget()) manually??
How is this possible?

Thank's for your support..
Last edited on
The constructor without arguments is the default constructor and that's the one that will be called if you don't explicitly specify which one you want to use.
1. calling a constructor of child that has exactly the same arguments like it's parent constructor:
Completely wrong.

There is 2 ways how base object constructor is called:
1) Explicitely call base constructor in derived constructor
2) If you do not explicitely call base constructor, default constructor for base object will be called implicitely.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

struct Base
{
    Base() {std::cout << "Base()\n";}
    Base(int) {std::cout << "Base(int)\n";}
};

struct Derived : Base
{
    Derived(int) {std::cout << "Derived(int)";}
};

int main()
{
    Derived x(42);
}
Base() 
Derived(int) 
Last edited on
Oh, thank you guys, I think I misunderstood something in my book...

So it doesn't matter which derived constructor I call, it's always the default base constructor() that is called as long as I do not call another one explicitly like this:
child::child() : parent(int specific_arguments)

Thank's for the fast and good support!
Topic archived. No new replies allowed.