Question Involving Inheritance

Hey guys, I have a question involving inheritance (hence the title xD). I'm trying to understand how initializing variables that a derived class inherits by calling the base classes constructor from the derived classes constructor works. This is the example I saw:

Base Class Definition:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#pragma once
#include<iostream>

class CBox
{
public:
	CBox(double lv = 1.0, double hv = 1.0, double wv = 1.0):
		m_length(lv), m_height(hv), m_width(wv) 
	{ std::cout << std::endl << "CBox constructor called"; }
	
	double volume() const
	{ return m_length * m_width * m_height; }

private:
	double m_length;
	double m_height;
	double m_width;
};

Derived Class:
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
#pragma once
#include<iostream>
#include "Box.h"

class CCandyBox : public CBox
{
public:
	char* m_Contents;

	CCandyBox(double lv, double hv, double wv, char* str = "Candy") :
		CBox(lv, wv, hv)
	{						
		std::cout << std::endl << "CCandyBox constructor2 called";
		m_Contents = new char[ strlen(str) + 1 ];
		strcpy_s(m_Contents, strlen(str) + 1, str);
	}	  
	CCandyBox(char* str = "Candy")
	{
		std::cout << std::endl << "CCandyBox constructor1 called";
		m_Contents = new char[ strlen(str) + 1 ];
		strcpy_s(m_Contents, strlen(str) + 1, str);
	}

	~CCandyBox()
	{ delete[] m_Contents; }
};  


From what I understand, when the CCandyBox constructor2 is called it's creating a sub-object of a CBox class which is initialized with the values passed to CCandyBox's constructor, and the CCandyBox object is then inheriting these values into its inherited m_length, m_height and m_width members.

Is this right at all...?
Last edited on
CCandyBox is a CBox, and more. In the derived class implementation, line 11 simply calls the constructor of the base class which fills out the "CBox" portion of the CCandyBox object.

(Your explanation has a level of indirection that is not actually present.)
Alright that makes sense. So when the CBox class is filling out the base class parts of CCandyBox it's filling it out with the values of lv, wv and hv. Makes sense :)
Topic archived. No new replies allowed.