0
#include <iostream>

using namespace std;
class A{
    public:
  A(){
      cout<<"a";
  }  

  A(int x){
      cout<<"x";
  }  
};

class B: public A{
  public:
  B(A ){
      cout<<"b";
  }  

};
int main()
{
    B b(10);
    return 0;
}

How is constructor of B accepting integer values? And why is parameterised constructor of A called first and then and default constructor?

2 Answers2

4

Since the constructor for B takes an A object, and an A object can be constructed from an integer, the compiler will call A(int) to construct the parameter to pass to B's constructor. This will result in the "x" being output. Since B's constructor does not supply an initializer for the A base class, the base class will be default constructed. This will output "a". Then the body of B's constructor will execute, causing the "b" to be output.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • I understood the first part, but I could not understand this "Since B's constructor does not supply an initializer for the A base class, the base class will be default constructed". Why does B need to supply an initialiser to A? Please explain your point.Thanks! – Rohit alawadhi Jan 22 '20 at 10:37
  • @Rohitalawadhi When you don't supply an initializer for a base class in a member-initializer-list, the base class subobject will be default initialized. Your B constructor takes an `A` object as a parameter, but does not pass the value on to the base class. To do that you'd want to write `B(A a): A(a) { cout << "B"; }`. When you do that, A's copy constructor (not the default constructor) will be invoked. – 1201ProgramAlarm Jan 22 '20 at 17:24
  • That means for "every" inherited class using base class' object as a parameter, the derived class needs to pass on the object using initialiser list so that if there are any modifications in the members of base class, it can reflect correct updated values for further program run. I assume this is the crux? – Rohit alawadhi Jan 27 '20 at 02:14
0

I don't meant to be rude, but for the sake of your code, don't do this kind of mess.

Firstly, you need to learn how to properly indent and space your code.

    class B: public A
    {
        public:
        B(A )
        {
            cout<<"b";
        }  
    };

When you write your code like this, it's become much more readable. (See this article: http://lazyfoo.net/articles/article02/index.php)

Now, anwsering your question:

1) The constructor of the class B takes an A object as parameter (you only forgot about naming your variable B( A foo ){...} ).

2) When you pass 10 as a argument, you are doing this in the process A foo(10) or this A foo = A(10). That's explain the first x.

3) The following a is from the A default constructor and the b is from the B constructor, ironically, the first one called.

isocppforbids
  • 389
  • 1
  • 12