My member function is not giving an output. Inheritance is involved. How can I fix that?

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <string>
using namespace std;

class Shape
{
public:
	Shape()
	{
		ID = "";
		name = "";
		height = 0;
		width = 0;
	}

	Shape(const Shape& _S)
	{
		ID = _S.ID;
		name = _S.name;
		height = _S.height;
		width = _S.width;
	}

	void setID(string _ID)
	{
		ID = _ID;
	}

	void setName(string _Name)
	{
		name = _Name;
	}

	void setHeight(double _Height)
	{
		height = _Height;
	}

	void setWidth(double _Width)
	{
		width = _Width;
	}

	string getID()
	{
		return ID;
	}

	string getName()
	{
		return name;
	}

	double getHeight()
	{
		return height;
	}

	double getWidth()
	{
		return width;
	}

	~Shape()
	{
		cout << "Destructor is called" << endl;
	}

protected:
	string ID;
	string name;
	double height;
	double width;
};

class Rectangle : public Shape
{
public:
	double getArea()
	{
		return height * width;
	}
};

int main()
{
	Rectangle rect;
	rect.setHeight(4);
	rect.setWidth(6);
	rect.getArea();

	return 0;
}


All I'm getting is
Destructor is called
.
Instead I should be getting
24
Instead I should be getting

Why do you think you should be getting some output? Your program never outputs anything other than "Destructor is called" so your program looks correct to me.


Try adding a cout << statement at line 90.
Why should it be printing
24
?
You didn't print it anywhere.
Did you mean to do:
 
std::cout << rect.getArea() << std::endl;
? If you don't store the return value, it'll just be thrown away.
Line 90: You call getArea(), but you ignore the returned value. As jlb pointed out, you have no cout of the area.

lines 12-13: IMO, height and width do not belong as members of Shape. They are specific to a Rectangle. Consider if you derive a Circle class from Shape. A Circle has a center point and a radius. Height and width are not appropriate.

Topic archived. No new replies allowed.