By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,913 Members | 1,263 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,913 IT Pros & Developers. It's quick & easy.

question about constructor

P: n/a
consider the following code:
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << 'A';
}
};
class B {
public:
B() {
cout << 'B';
}
private:
A a;
};
int main()
{
B b;
}

Why the output is AB not BA ?
And when the A::A() be called ?

Jul 23 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
"July" <ju**********@yahoo.com> wrote in message
news:11*********************@o13g2000cwo.googlegro ups.com
consider the following code:
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << 'A';
}
};
class B {
public:
B() {
cout << 'B';
}
private:
A a;
};
int main()
{
B b;
}

Why the output is AB not BA ?
And when the A::A() be called ?


The order of construction is:

1. base object constructor.
2. member object constructor.
3. body of own constructor function.
--
John Carson
Jul 23 '05 #2

P: n/a
July wrote:
consider the following code:
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << 'A';
}
};
class B {
public:
B() {
cout << 'B';
}
private:
A a;
};
int main()
{
B b;
}

Why the output is AB not BA ?
And when the A::A() be called ?

Obviously, the member object of the class is first constructed.

--
Best Regards

Xie Yubo
Email: xi*****@gmail.com Website: http://xieyubo.cn/
Harbin Institute of Technology
Phone: 86-451-86416614 Fax: 86-451-86413309
Jul 23 '05 #3

P: n/a
On 17 Jul 2005 06:22:43 -0700, "July" <ju**********@yahoo.com> did
courageously avow:
consider the following code:
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << 'A';
}
};
class B {
public:
B() {
cout << 'B';
}
private:
A a;
};
int main()
{
B b;
}

Why the output is AB not BA ?
And when the A::A() be called ?


Because the base class is called first, and then any derived classes,
in order?
Ken Wilson
"Coding, coding, over the bounding main()"
Jul 23 '05 #4

P: n/a

"July" <ju**********@yahoo.com> wrote in message
news:11*********************@o13g2000cwo.googlegro ups.com...
consider the following code:
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << 'A';
}
};
class B {
public:
B() {
cout << 'B';
}
private:
A a;
};
int main()
{
B b;
}

Why the output is AB not BA ?
And when the A::A() be called ?


Because you need to build the engine *before* you can start building the
car. The same goes with any other component in such a "composition".

Jul 23 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.