Why am I getting zeros back from a class using inheritance

Here's my code:

Header File
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <string>
using namespace std;

class Dimensions {
private:
	int height;
	int width;
public:
	Dimensions();
	Dimensions(int,int);
	int getHeight();
	int getWidth();
	int getArea();
};

class Cube: public Dimensions {
private:
	int length;
public:
	Cube();
	Cube(int);
	int getLength();
	int getVolume();
};

Dimensions::Dimensions() {
	height = 0;
	width = 0;
}

Dimensions::Dimensions(int x, int y) {
	width = x;
	height = y;
}

int Dimensions::getHeight() {
	return height;
}

int Dimensions::getWidth() {
	return width;
}

int Dimensions::getArea() {
	return getWidth() * getHeight();
}

Cube::Cube() {
	length = 0;
}

Cube::Cube(int z) {
	length = z;
}

int Cube::getLength() {
	return length;
}

int Cube::getVolume() {
	return getArea() * getLength();
}


Implementation
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
#include "refresher.h"
using namespace std;

void main(void)
{
	int x = 0;
	int y = 0;
	int z = 0;

	cout << "Enter the width: ";
	cin >> x;
	cout << endl << "Enter the height: ";
	cin >> y;

	Dimensions _dims(x,y);

	cout << endl << "X = " << _dims.getWidth() << 
        endl << "Y = " << _dims.getHeight() << endl << "Total Area: " 
        << _dims.getArea() << endl;

	cout << "Enter the depth: ";
	cin >> z;

	Cube _cube(z);

	cout << endl  << endl << "X = " << _dims.getWidth() 
        << endl << "Y = " << _dims.getHeight() << endl << "Z = " 
        << _cube.getLength() << endl << endl << "Total Volume: " 
        << _cube.getVolume() << endl;


	system("PAUSE");
}


Everything goes well until I get to the last statement before the pause. I think it's calling my Dimensions constructor again when the getVolume() function is called. Can someone explain to me, why?

Thanks!
Last edited on
Why am I getting zeros back from a class using inheritance?
you are getting zerros because you didn't initialze heigth and width for _cube object, you initialize just length (z).
so width and height in _cube object are both an big zerro.

object _dims is (which holds heigth and width is independed of _cube
also _cube is independed from _dims, they dot now nothing about each oter cose these are two objects not one.

why?
object _cube has everyting what _dims has but _dims does not have everyting what _cube has

so?
to initialize object as you intended in your code above delete _dims and call all metods for _cube only cos _cube is _cube and _dims in same time because _cube has inherit _dims.
that is inheritance.

call same member functoins on _cube as you would on _dims and you got it.
Last edited on
That makes perfect sense! Thanks for your help!
Topic archived. No new replies allowed.