delegat
delegat

Reputation: 1

C++ virtual function not recognized

I am using CodeBlocks and I have the following code which does not compile.

(It is about some C++ pitfalls so the only thing I want to ask is why it does not compile)

The code is as follows:

#include <iostream>
using namespace std;

class Shape
{
        public:
                Shape();
                virtual void reset();
        private:
                int color;
};

class Point : public Shape
{
        private:
        double a,b;
};

void Shape::reset()
{
        cout<<"Shape reset\n";
}

void Point::reset()
{
        Shape::reset();
        cout<<"Point reset";
}

Shape::Shape()
{
        reset();
}

int main()
{
        Shape s;
        Point o;
}

I get the following error:

no `void Point::reset()' member function declared in class `Point'

Upvotes: 0

Views: 260

Answers (2)

Rivasa
Rivasa

Reputation: 6750

It should be declared like this instead:

class Shape
{
       public:
               Shape();
               virtual void reset(){};
       private:
               int color;
};

Notice the brackets, since the virtual function does nothing, you can just add the brackets in the declaration. Since it is a virtual function it is designed to be redefined when inheriting the base class. So can't really call Shape::reset() in your Point::reset() function. Also in your Point class, you need to redefine the new function. Like this:

class Point : public Shape
{
     public:
         void reset();
}

then you can use the function as Point::reset.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

You need to add a declaration of the function to your Point class body:

class Point : public Shape
{
public:
    virtual void reset();
private:
    double a,b;
};

(The virtual is unnecessary, because it's declared virtual in the base class. But it's helpful to add it as a reminder.)

Upvotes: 6

Related Questions