I have a public derived class called Rectangle and I'm trying to have a virtual function in Rectangle called calcArea() use the setter function called setArea() but I get 'double BasicShape::area' is private
I guess it's because the abstract base class is never and can never actually be instantiated but the assignment I'm doing says that it should be private and be used to hold the shape's area. I mean to me it makes much more sense to make it protected but... this is what the assignment says to do.
#ifndef BASICSHAPE_H
#define BASICSHAPE_H
class BasicShape
{
private:
double area;
public:
double getArea();
//because area is private and is inaccessable to members of the derived
//classes
void setArea(double a);
virtualdouble calcArea() const = 0;
};
#endif
And here is its .cpp file
1 2 3 4 5 6 7 8 9 10 11 12 13
#include "basicshape.h"
double BasicShape::getArea()
{
return area;
}
//because area is private and is inaccessable to members of the derived
//classes
void BasicShape::setArea(double a)
{
area = a;
}
#ifndef RECTANGLE_H
#define RECTANGLE_H
#include "basicshape.h"
class Rectangle : public BasicShape
{
private:
long width;
long length;
public:
Rectangle(long w, long l);
long getWidth();
long getlength();
virtualdouble calcArea() const;
};
#endif
and my rectangle.cpp file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include "rectangle.h"
Rectangle::Rectangle(long w, long l)
{
width = w;
length = l;
}
double Rectangle::calcArea() const
{
//need to convert area from long to double because
//area variable in basicShape.h is a double
long longArea = width * length;
double doubleArea = static_cast<double>(longArea);
setArea(area);
}
Thanks, Mikey. I changed Rectangle's calcArea() to this and now the error about area being private is gone :D I have a new error passing 'const Rectangle' as 'this' argument of 'void BasicShape::setArea(double)' discards qualifiers [-fpermissive] but at least that old one is gone!
1 2 3 4 5 6 7 8 9 10 11
double Rectangle::calcArea() const
{
//need to convert area from long to double because
//area variable in basicShape.h is a double
long longArea = width * length;
double doubleArea = static_cast<double>(longArea);
setArea(doubleArea);
}
You've defined calcArea() to be const, but you're trying to call a non-const method. That's illegal.
If the purpose of calcArea() is to change the state of the object (by changing the value of the area data member), then it shouldn't be defined as const.
#ifndef BASICSHAPE_H
#define BASICSHAPE_H
class BasicShape
{
private:
double area;
public:
double getArea();
//because area is private and is inaccessable to members of the derived
//classes
void setArea(double a);
virtualdouble calcArea() = 0;
};
#endif