Search code examples
c++cloneabstract

Cannot initiate an abstract class because members are abstract


I am new to polymorphism, this is a similar question to this but the solution didn't help me. The exact error is:

Circle.cpp(34) : error C2259: 'Circle' : cannot instantiate abstract class due to following members: 'void Shape::particle(const Ray &,const int&)' : is abstract

I have tried to read up on this and what I think is that the clone() member function,calls Circle's copy constructor to copy the state of this into the newly created Circle object and tries to initialize the 'particle' (which it cant do). If I am right: how do I correct this? If I am wrong...what is it doing (what am I doing wrong) and how do i correct it.

class Shape {
public:

virtual void particle(const Ray& ray, const int& count) = 0;      
...
virtual Shape* clone()  const = 0;   
private:
vector<Ray>  incoming_ray; 
vector<int>  counts;
};

class Circle : public Shape {
public:
Circle* clone()  const;   //covariant return type
virtual void
particle(const Ray& ray, const int& count);
 ...
};

And then

Circle* Circle::clone()  const { return new Circle(*this); }

void
Circle::particle(const Ray& rays, const int& count){
incoming_ray.push_back(inc_ray);
counts.push_back(counts);};

I tried

virtual void particle(const Ray& ray, const int& count) const = 0; 
                                                          ^

but still got the same error?

Thanks


Solution

  • virtual void particle(const Ray& ray, const int& count) const = 0;
                                                            ^^^^^^
    

    Makes it a altogether different method. And is not same as:

    virtual void particle(const Ray& ray, const int& count) = 0;
    

    Eventually, what you have is a new method in your derived class which is pure virtual, It does not override the Base class pure virtual method. Since there is no overidding it leaves your derived class with an inherited pure virtual function which it doesn't implement and it makes your derived class as Abstract class as well.

    To override a Base class virtual method You need to have exact same definition of the method in Base class to override it(Co-variant types are allowed though).