Some doubts about inheritance

Oct 18, 2010 at 7:31pm
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
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <conio.h>
using namespace std;

class C1 {
	protected:
		float m_c1;
	public:
		C1(float x) { m_c1 = x; }
		void print() { cout << "C1:" << m_c1 << endl; }
};
class C2 : public C1 {
	protected:
		float m_c2;
	public:
		C2(float x) : C1(1) { m_c2 = x; }
		void print() { cout << "C2:" << m_c1 + m_c1 << endl; }
};
class C3 : public C2 {
	protected:
		float m_c3;
	public:
		C3(float x) : C2(2) { m_c3 = x; }
		void print() { cout << "C3:" << m_c1 + m_c2 + m_c3 << endl; }
};

int main()
{
	C1 c1(2.3);
	C2 c2(5.7);
	C3 c3(1.9);
	c1.print();
	c2.print();
	c3.print();
	getch();
	return 0;
}


1) Why does the function 'c1.print();' prints '2.3' instead of '1', if the fuction 'c2.print();' prints '2' and 'function 'c3.print(); prints '4.9'.
Oct 18, 2010 at 8:01pm
1) C1 prints whatever it is constructed with.

2) Inspect lines 16 and 17 very closely. Line 16 invokes the base constructor C1 with a value of 1. Line 17 is printing m_c1 + m_c1, which is 1 + 1.

3) Similarly, in C3, m_c1 is 1, m_c2 is 2, and m_c3 is 1.9, totaling 4.9.
Last edited on Oct 18, 2010 at 8:02pm
Oct 18, 2010 at 8:24pm
I think I understod, but line 23 doesn't invokes the base constructor C1. Or not?
Oct 18, 2010 at 8:59pm
It does. C3 inherits from C2, which inherits from C1. The constructors are called in order from the base class up to the most derived subclass.
Topic archived. No new replies allowed.