-
Polymorphism Problem
I was writing this simple polymorphism program:
Shape.h
Code:
#ifndef SHAPE_H
#define SHAPE_H
#include <string>
using namespace std;
class Shape
{
public:
virtual double getArea() const;
virtual double getVolume() const;
virtual string getName() const = 0;
virtual void print() const = 0;
};
#endif
Shape.cpp
Code:
#include <iostream>
#include "Shape.h"
using namespace std;
double getArea() const
{
return 0.0;
}
double getVolume() const
{
return 0.0;
}
When I compile Shape.cpp using Visual C++ 6.0 it come out with errors message:
Shape.cpp(7) : error C2270: 'getArea' : modifiers not allowed on nonmember functions
Shape.cpp(12) : error C2270: 'getVolume' : modifiers not allowed on nonmember functions
-
>> double getArea() const
In Shape.cpp
Code:
double Shape::getArea() const { ... }
Same with getVolume()
-
twomers already answered your question, but might also consider these pointers:
1. Fully qualify all names used in header files. For example, use std::string instead of string. The reason is that someone who includes your header file might have say, a class named string (for guitar strings?), and consequently there will be a name collision.
2. Since Shape is a base class, it should have a virtual destructor. I am not entirely sure if this matters when you do not have any member variables, but it is good practice anyway.
-
It matters. Functions with virtual member functions always have state. (Typically the vptr, but that's an implementation detail.) Deleting an object through a base pointer is always undefined behaviour if the base doesn't have a virtual destructor. That's just how it is. Just because one implementation might not crash is no reason to omit it.