Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure Virtual Function error in factory design pattern

studying for a final and decided to build a program which makes use of pure virtual functions and polymorphism. i am stuck on a really weird error maybe i am missing something.

This is the Shape abstract class

#ifndef Shape_hpp
#define Shape_hpp

#include <stdio.h>
#include <string.h>

class Shape{
    const char* name;
public:
    Shape(const char* abc);
    virtual double getPerimeter()=0;
    virtual double getArea()=0;
};

#endif /* Shape_hpp */

The Shape .cpp implementation file

#include "Shape.hpp"

Shape::Shape(const char *shape){
    name = shape;
}

The Circle Header file

#ifndef Circle_hpp
#define Circle_hpp

#include "Shape.hpp"
#include <stdio.h>

class Circle:public Shape{
    double m_radius;
public:
    Circle(double rad);
    double getRadius();            
};

#endif /* Circle_hpp */

The circle .cpp implementation file

#include "Circle.hpp"
#include "Shape.hpp"

Circle::Circle(double rad):Shape("Circle"){
    m_radius = rad;
}

double Circle::getRadius(){
    return m_radius;
}

double Circle::getPerimeter(){
    return (2 * 3.14 * m_radius);
}

double getArea(){
   return 0;
}

I declared the two pure virtual functions in the abstract "shape" class and am accessing the public of shape class in circle header file, if i declare the pure virtual functions in the circle class it will make it abstract... the error says "Out-of-line definition of 'getPerimeter' does not match any declaration in 'Circle'"

Am i missing something or am i thinking about this the wrong way..

Help would be appreciated. Thanks!

like image 861
Celery Avatar asked Jul 21 '26 01:07

Celery


2 Answers

You need to declare all member functions that you define. So in class Circle you need to add:

virtual double getPerimeter();

Or better in C++11:

double getPerimeter() override;
like image 182
John Zwinck Avatar answered Jul 22 '26 14:07

John Zwinck


You're defining Circle::getPerimeter() in your .cpp file but there is no member function getPerimeter() in the Circle class declaration. All pure virtual functions need to be overriden in a derived class in order for the class to become concrete. So yes, virtual double getPerimeter(); and override if you're using C++11.

Also, it's good practice to declare simple getters const.

like image 41
Zoli Avatar answered Jul 22 '26 15:07

Zoli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!