0

Maybe I'm just asking badly my question to Google, but I don't find an answer to my problem. My trouble is that my inherited constructor calls my default base constructor and I don't really get why. Here are my simplified version.

Example:

A.cpp

#include <iostream>
#include "A.h"

using namespace std;

A::A()
{
    cout << "A" << endl;
}

B.cpp

#include <iostream>
#include "B.h"

using namespace std;

B::B()
{
    cout << "B" << endl;
}

B::B(int x)
{
    cout << "B" << x << endl;
}

Source.cpp

#include <iostream>
#include "A.h"
#include "B.h"

using namespace std;

int main() {
    B * b = new B();
    cout << "---" << endl;
    B * b2 = new B(2);

    system("PAUSE");
    return 0;
}

Output:

A
B
---
A
B2
Press any key to continue . . .

I just want to see what B constructor do. Like this:

B
---
B2
Press any key to continue . . .
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Do you have any inherited constructor there? Also, to successfully build an object of type `B` you also need to invoke `A`'s ctor... – Adriano Repetti Oct 16 '17 at 13:14
  • 6
    Sounds like you should revisit a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) You always have to construct the base part of a derived class. – NathanOliver Oct 16 '17 at 13:14
  • 1
    You haven't show the definition of your classes and you haven't stated out-right that `B` derives from `A`. I guess we can infer the inheritance from the question's title and the provided output. – François Andrieux Oct 16 '17 at 13:15
  • 1
    You are not showing some important code. See [mcve]. My guess is that you wrote `class B : A {` in your `B.h` which means "a B is an A" which means that in order to create a `B` you also must have an `A` that needs to be constructed. – nwp Oct 16 '17 at 13:15
  • #pragma once #include "A.h" class B : public A { public: B(); B(int); ~B(); }; – Mihók Balázs Oct 16 '17 at 13:19

1 Answers1

1

Because the parent class might be responsible for e.g. initialising member variables (including potentially allocating memory) that the subclass later depends on.

Steve
  • 1,747
  • 10
  • 18