Search code examples
c++inheritanceoverridingvirtualpure-virtual

Virtual pure functions


I understand that a pure virtual function inside of a class makes that class abstract. That means I can't create objects with that class and that I must override that virtual function in all derived classes.

I have the following code:

class Forma{
    protected:
        double x,y;
    public:
        Forma(double h=0, double v=0);
        virtual double Arie() const;
        virtual double Perimetru() const=0;
};

class Dreptunghi: public Forma{
    public:
        Dreptunghi(double h=0, double v=0);
        virtual double Arie() const;
        virtual double Perimetru() const;
};

class Cerc:public Forma{
    protected:
        double raza;
    public:
        Cerc(double h=0, double v=0, double r=0);
        virtual double Arie() const;
        virtual double Perimetru() const;
 };

 Forma::Forma(double h,double v){x=h; y=v;}
 double Forma::Arie() const{return x*y;}
 double Forma::Perimetru() const{return x+y;}

 Dreptunghi::Dreptunghi(double h,double v){Forma(h,v);}
 double Dreptunghi::Arie() const{return x*y;}
 double Dreptunghi::Perimetru() const{return 2*x+2*y;}

My errors are the following:

33 53 [Error] cannot allocate an object of abstract type 'Forma'
4 7   [Note] because the following virtual functions are pure within 'Forma':
31 9  [Note] virtual double Forma::Perimetru() const

How can I fix this? Thank you.


Solution

  • The syntax for passing arguments to the base class is as follows:

    Dreptunghi::Dreptunghi(double h, double v) : Forma(h, v) {}
    

    The way you wrote it, it'd instead try to create an instance of Forma, which of course isn't allowed.