Inheritance Help!!!!!!!!!!!

When I compile, i get an error stating that I need a return value for my GetArea() function inside of "shape.cpp" but I set my return values in my derived class "rectangle.cpp". What do I 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
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
//----------------------
// BASE CLASS - shape.h
//----------------------

#include <iostream>
using namespace std;

#ifndef _SHAPE_
#define _SHAPE_

class Shape
{
public:
	void SetWidth(float);
	void SetHeight(float);
	float GetArea();

protected:
	float width;
	float height;
};

#endif

// -----------------------
// BASE CLASS - shape.cpp
//------------------------

#include "shape.h"
#include "rectangle.h"

void Shape::SetWidth(float wid)
{
	width = wid;
}

void Shape::SetHeight(float hei)
{
	height = hei;
}

float Shape::GetArea()
{
   // ????????
}

//-----------------------------
// DERIVED CLASS - rectangle.h
//-----------------------------

#include "shape.h"

#ifndef _RECTANGLE_
#define _RECTANGLE_

class Rectangle : public Shape 
{
public:
	float GetArea();
};

#endif 

//-------------------------------
// DERIVED CLASS - rectangle.cpp
//-------------------------------

#include "shape.h"
#include "rectangle.h"

float Rectangle::GetArea()
{
	return (width * height);
}
float GetArea()=0; in class shape

and remove
1
2
3
4
float Shape::GetArea()
{
   // ????????
}


generic shape doesnt have area anyway, specific shapes do
Last edited on
Well ... first of all if you want to redefine a method from the base class, you should declare it virtual in the base class:
 
virtual float GetArea();


This is the way to do when you want to redefine methods in derived classes. Then, because the Shape is something generic, so generic that you probably don't want to have an instance of this class (since it wouldn't have any sens), you will wish to make it an abstract class (a class that cannot be instantiate). To do so, it is enough to set one of its methods to 0 as mentioned by codewalker:
 
virtual float GetArea() = 0;

And doing so, you don't need body for this method in the generic class, as mentioned by codewalker.

Hope it clarifies the story ;)
Last edited on
It compiles perfectly now. Thank you!
Topic archived. No new replies allowed.