Class inheritence guide

Apr 20, 2017 at 1:55am
what does the lines i indicated do?

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
class A
{
	protected:
		int y;
	private:
		int z;
	public:
		int x;
		
		A(int a, int b, int c):x(a), y(b), z(c) // constructor but that colon and x(a), y(b). what does this do
		{
		}
		
		void display()
		{
    		cout << "x is " << x << endl;
  			cout << "y is " << y << endl;
	  		cout << "z is " << z << endl;
		}
};
class B : public A
{
	private:
		int num; 
	public:
	B(int x, int y, int z, int extra): A(x, y, z), num(extra) // same here its a constructor but what does the stuff after the colon do?
	{
	}

	void display()
	{
    	cout << "x is " << x << endl;
    	cout << "y is " << y << endl;
    }
	   
};
Apr 20, 2017 at 1:58am
That's a member initialization list :+)

http://en.cppreference.com/w/cpp/language/initializer_list

The x(a) is an example of direct initialization.

http://en.cppreference.com/w/cpp/language/initialization

Edit:

The A(x, y, z) calls the base class constructor
Last edited on Apr 20, 2017 at 2:01am
Apr 20, 2017 at 2:05am
its basicaly like this right?
1
2
3
4
5
6
A::A(int a, int b, int c)
{
      x = a;
      y = b;
      z = c;
}
Apr 20, 2017 at 3:20am
Yes, but better.

Classes get their member variables initialised before the constructor starts (the opening brace), either by the member initializer list or default initialisation. When one has assignment statements in the constructor body, they get re-initialised - which is a little inefficient.
Topic archived. No new replies allowed.