Inheritance explanation

Hi,
i have a question: for this main:
int main()
{
B *b=new B;
}
why does 1 printed twice?
thnks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  #pragma once
#include <iostream>
using namespace std;

class A 
{
public:
	A();
	//A(A& a)		{cout<<"(2)"<<endl;}
	virtual void f()  {cout<<"(3)"<<endl;}	
	void g()	{cout<<"(4)"<<endl;}
	virtual A h(){f(); cout<<"(5)"<<endl; return *this;}
	~A();
};

class B : public A
{
	int x;
	A a1;
   public:
	B():x(0)			{cout<<"(7)"<<endl;}
	B(int num):x(num)	{cout<<"(8)"<<endl;}
	//B(B &b)			{cout<<"(9)"<<endl;}
	virtual void f()	      {g();cout<<"(10)"<<endl;}
	void g()		      {cout<<"(11)"<<endl;}
 	B k()		           {cout<<"(12)"<<endl; return *this;}
    ~B()	  		      {cout<<"(13)"<<endl;}
};
"1" won't print at all with the code you've posted. There is no cout with "(1)".

Assuming you meant for A's constructor to output "(1)" at line 8, the reason new B would display "(1)" twice, is that new invokes B's default constructor. Because B inherits from A, A's default constructor is invoked displaying the first "(1)". B also includes an instance of A at line 19. That also causes A's default constructor to be invoked resulting in a second display of "(1)".
Topic archived. No new replies allowed.