0
#include <iostream>
using namespace std;
class A{
    public:
    A(){
        cout << "Hello World";
    }
};
class B:public A{
    public:
    B(){
        cout << "World";
    }
};
int main(){
    B obj1;
    return 0;
}

Why does this program print Hello WorldWorld, shouldn't it print World because I have created object of class B, so why is the constructor of A being called?

proglove
  • 15
  • 5
  • 1
    It will print both. A's constructor will be called first, then B's – Ted Lyngmo Apr 04 '21 at 17:33
  • But my question is: why is the constructor of A being called? @TedLyngmo – proglove Apr 04 '21 at 17:34
  • Why would you want members of `A` to not be initialized? They would not be initialized by the constructor of `B`. Maybe `B` does not even have access to all members of `A` and does it know what values to initialize member variables of `A` – drescherjm Apr 04 '21 at 17:55

1 Answers1

2

Conceptually, a base class becomes an unnamed sub object in the derived class, whose members are available in the same scope without extra qualification, and must be initialized.

You cannot avoid that initialization - which means a relevant constructor will be called or if it cannot be constructed then compiler will not allow you to inherit.

What you probably mean is whether the constructor should have overridden the base version, the simple answer is it cannot. If you want that effect - which will not work in constructors in a common sense way - you need to use virtual functions and overriding.

Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32