Reputation: 19
I want to create a shape class to draw rectangles and circles in Oxy and out of the area. I have to use virtual function, and it goes to errors:
43 10 D:\Cpp\TurboC4\OOPCpp\shape.cpp [Error] cannot declare field 'Circle::r' to be of abstract type 'Shape' 6 7 D:\Cpp\TurboC4\OOPCpp\shape.cpp because the following virtual functions are pure within 'Shape': 18 18 D:\Cpp\TurboC4\OOPCpp\shape.cpp virtual float Shape::area()
Here's my code:
class Shape{
public:
int x,y;
public:
void set_data (int a,int b){
x=a;
y=b;
}
void input(){
cout<<"x= "; cin>>x;
cout<<"y= "; cin>>y;
}
virtual float area()=0;
};
class Rectangle: public Shape{
public:
Rectangle(){
x=0;
y=0;
}
Rectangle(int x,int y){
this->x=x;
this->y=y;
}
void input(){
cout<<"Enter value of width and height: ";
cin>>x;
cin>>y;
}
float area(){
return x*y;
}
};
class Circle: public Shape{
protected:
Shape r;
public:
Circle(){
r.x=0;
r.y=0;
}
//center of Circle: default(0,0) , r is 1 point in the circle.
Circle(int x,int y){
r.x=x;
r.y=y;
}
void nhap(){
cout<<"Enter values x,y of r: ";
cin>>x;
cin>>y;
}
virtual float area(){
float a=sqrt(r.x*r.x+r.y*r.y);
return 3.14*a*a;
}
};
class ArrayOfShape{
private:
int n;
Shape **a;
public:
void nhap(){
int hinh;
cout<<"input number of shape: ";
cin>>n;
a=new Shape*[n];
for (int i=0;i<n;i++){
cout<<"\nEnter shape (1:rectangle,2:circle): ";
cin>>hinh;
if (hinh==1){
Rectangle *p=new Rectangle();
p->nhap();
a[i]=p;
}
else{
if(hinh==2){
Circle *e=new Circle();
e->input();
a[i]=e;
}
else{
cout<<"Invilid input";
}
}
}
}
void area(){
for (int i=0;i<n;i++)
cout<<"\nArea of shape"<<i+1<<" : "<<a[i]->area();
}
};
int main(){
ArrayOfShape a;
a.input();
a.area();
}
Upvotes: 0
Views: 86
Reputation: 121599
The problem is here:
class Circle: public Shape{
protected:
Shape r; // Wrong
Because Shape is a pure virtual function, you cannot create an instance of it (which is precisely what Shape r
tries to do).
Possible solution:
class Circle: public Shape{
protected:
int x, y
...
public Circle() {
x = y = 0; // Do you really need "r" at all? Why not just x and y?
...
ALSO:
If you're really using Turbo C++ ... please don't. It's 20 years out of date ... and it matters. Especially if you're learning. There are plenty of free and/or Open Source C++ compilers that would probably serve you much better...
Upvotes: 0
Reputation: 409136
When you declare the member variable r
in Circle
, then you declare an instance of the Shape
class. Since Shape
is an abstract class, that is not possible.
You need to make the variable r
either a reference or a pointer.
After reading your code a little more, you probably should not use a member variable here at all, but use the x
and y
members you inherit from the Shape
base class. Like you already do in the Rectangle
class.
Upvotes: 1