Example of simple C++ classes

In this example we have to describe some geometrical figures: we design a class "Figure", containing the base features for each figure and two classes: "Circle" and "Square", containing specific features for the different geometries.

The "Figure" class has the "area" feature, a feature common to all figures.

The classes Square and Circle inherit Figure, gaining the area feature, but they have their own way to compute the area, and also specific members describing their peculiarities, as the side for the square and the radius for the Circle.

Really, this is a simple case, so simple that here the machinery of object oriented programming could (and should) be avoided, but examples have to be simple.

Here the C++ program, implementing the example:

class Figure {
        private:
          float area;

        public:

          float getArea(){
            return area;
          }

        protected:
          void setArea(float area0){
            area = area0;
          }

};

class Circle : public Figure {

        private:
          double radius ;

        public:
          Circle(float radius0) {
            radius=radius0
            float a;
            a=pow(radius, 2) * 3.14 ;
            setArea(a) ;
          }

          float getRadius() {
            return radius ;
          }
};

class Square : public Figure {

        private:
          double side ;

        public:
          Square(float square0) {
            square=square0
            float a;
            a=pow(square, 2) ;
            setArea(a) ;
          }

          float getSide() {
            return side ;
          }
};

The Figure class has the area feature but as a private member, it can't be seen outside the class; to access the area you have to use the function "getArea" and "setArea"; these are the interface of the "Figure" class. Most programmers like an interface made only by functions, to avoid the direct access to class variables, so the "area" variable is not made public. "setArea" is protected, only derived colasses can use it.

"Square" and "Circle" have a constructor function, (the function with the same name of the class), used to compute, in different ways, the area. "side" and "radius" are private members. The interface of thesse classes consists of the functions: getSide, (getRadius for the circle) and GerArea.

The main program instantiates two objects: a circle and a square, giving th size or side to their constructors.

int main(int argc,char * argv[])
{
    float r=1,0;

    Circle c(r) ; // instantiate the object c, a circle, with radius r
    Square s(r) ; // instantiate the object s, a square, with size r

    cout << "circle; radius, and area are: ",c.getRadius() <<",",<<c.getArea() << endl ;
    cout << "square; side, and area are: "  ,s.getSide()   <<",",<<s.getArea() << endl ;

}



This text is released under the "Creative Commons" license. Licenza Creative Commons