0

HI and good day to all,

Since my 2nd year of my uni life, i have hardly touch C++ programming especially OOP in C++.Now starts my revision on C++ OOP.
Since I have forgotten many OOP knowledge there is a question I wish to ask.

Below is my code.

#include <iostream>

using namespace std;

class B
{
public:
    B()
    {
        cout<<"B::B()\n";
    }
    B(int n)
    {
        cout<<"B::B("<<n<<")\n";
    }
};

class D:public B
{
    private:
    B b;
    public:
    D()
    {
        cout<<"D::D()\n";
    }
    D(int n):B(n)
    {
        b = B(-n);
        cout<<"D::D("<<n<<")\n";
    }
};
int main()
{
    D d(3);
    return 0;
}

The output i got is as below:

B::B(3)
B::B()
B::B(-3)
D::D(3)

I hope that there is someone here kindly explain to me why i get the 1st 2 line of output(which is B::B(3) and B::B()) instead of the last 2 line of output???
Thank you.

2
Contributors
2
Replies
30
Views
2 Years
Discussion Span
Last Post by vergil1983
1

"instead"? Don't you get all four?

Anyway what happens is that first the super class constructor is called (causing "B::B(3)"), then the member constructors are called (causing "B::B()" because of your member b) and then the body of the constructor is executed (causing the other two outputs).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.