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.

"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).

Thank you for your reply although I still need time to digest it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.