Question

I've got few classes:

class Shape{
/* ... */
public:
    virtual double field() = 0;
    virtual double circumference() = 0;
};

class Circle: public Shape{
protected:
    Point center;
    double R;
public:
    Shape(Point &p1, double R){
        this->center=p1;
        this->R = R;
    }
    double field(){
        return M_PI *this->R * this->R;
    }
    double circumference(){
        return 2* M_PI * this->R;
    }
    friend ostream & operator<<(ostream &ostr, const Circle &f);
};

The friend overloaded operator is:

ostream & operator<<(ostream &ostr, const Circle &f){
    ostr<<"Radius: "<<f.R<<endl;
    ostr<<"Circumference: "<<f.circumference()<<endl;
    ostr<<"Field: "<<f.field()<<endl;
    return ostr;
}

And the main code contains:

/* ... */
Point p = {0,0};
Circle c = Circle(p, 10);
cout<<c;

The error is inside ovefloaded operator<<:

passing 'const Circle' as 'this' argument of 'virtual double Circle::field()'

But when I change double field(){ to double field() const{ I get:

Cannot allocate an object of abstract type 'Circle'

I suppose I don't fully understand usage of virtual. Can someone please explain what am I doing wrong?

Was it helpful?

Solution

Circle becomes abstract as soon as you change it's function field() to const, because field() const is actually a totally different method than field(), which is why field() then remains undefined in Circle so it is abstract.

I would suggest you use the new C++11-ish keyword override in Circle::field() to communicate to the compiler that you actually intend to override a virtual method. The compiler then refuses to compile if the field function in your inherited type is not present and/or compatible in/with any virtual method in the base class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top