Polymorphism (shapes) object
Apr 16, 2014 at 10:23am UTC
Hi everyone! Im doing a classic example of polymorphism with shapes but im stuck with the first example of a shape (circle) which is a derived class from the base (shapes). The problem is that i canĀ“t create an object of the class circle and i dont understand why.... can someone help me?
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
#include <iostream>
#include <string>
#include <list>
#include <cmath>
using namespace std;
class Shape{
public :
virtual void setX(int xcor);
virtual void setY(int ycor);
virtual int getX();
virtual int getY();
virtual double area();
virtual double perimetro();
};
class Circle : public Shape {
private :
int x, y;
double raio;
public :
Circle(int xcor , int ycor , double r){
x = xcor;
y = ycor;
raio = r;
}
void setX(int xcor){
x = xcor;
}
void setY(int ycor){
y = ycor;
}
void set_raio(double r){
raio = r;
}
double get_raio(){
return raio;
}
int getX(){
return x;
}
int getY(){
return y;
}
double area(){
return ((pow(2,raio))* 3.14);
}
double perimetro(){
return ((raio * 2) * 3.14);
}
};
int main()
{
Circle ob(2,3,2); // when I create and object i get error
}
Last edited on Apr 16, 2014 at 10:40am UTC
Apr 16, 2014 at 10:35am UTC
you need to implement all functions you declared unless you make them pure virtual like
virtual void setX(int xcor) = 0 ;
then you need to implement the function in the derived class
Apr 16, 2014 at 10:43am UTC
Hi luis123,
You have declared funtions in the base class but definition are not present, that is why your getting errors.
Please provide the function definition or mark the funtion as
pure virtual (=0) .
Modified Code is shown in bold
1 2 3 4 5 6 7 8 9 10
class Shape{
public :
virtual void setX(int xcor)=0 ;
virtual void setY(int ycor)=0 ;
virtual int getX()=0 ; // const ?
virtual int getY()=0 ;
virtual double area()=0 ;
virtual double perimetro()=0 ;
};
Last edited on Apr 16, 2014 at 10:44am UTC
Apr 16, 2014 at 10:43am UTC
For the initialization of an instance of Shape(or Circle) to be possible, there must be an implementation of Shape::setX(int), Shape::setY(int) and all Shape functions which aren't pure virtual(in this case, all).
So since you do not need implementation of the general class(as implied in your code), you could do this:
1 2 3 4 5 6
virtual void setX(int xcor){}
virtual void setY(int ycor){}
virtual int getX() const {}
virtual int getY() const {}
virtual double area(){}
virtual double perimetro(){}
Aceix;
Apr 16, 2014 at 10:54am UTC
Thank you everyone! I understood the concept and I can now code with no errors :D . Greeting to erveryone!
Last edited on Apr 16, 2014 at 10:54am UTC
Topic archived. No new replies allowed.