Menu
Coddy logo textTech

Rectangle Implementation

Part of the Object Oriented Programming section of Coddy's C journey — lesson 46 of 61.

challenge icon

Challenge

Easy

Let's continue building the Shape Drawer project by implementing the Rectangle — another concrete shape that embeds the base Shape struct, just like we did with Circle.

Building on your existing project, you'll add rectangle functionality across these files:

  • shape.h: Keep your base Shape interface with the DrawFunc and AreaFunc function pointer types from the previous lessons.
  • circle.h and circle.c: Keep your Circle implementation from the previous lesson.
  • rectangle.h: Define your Rectangle struct here. A rectangle embeds Shape as its first member and adds width and height fields (both double). Declare a constructor function create_rectangle that takes width and height parameters and returns a Rectangle by value.
  • rectangle.c: Implement the rectangle-specific behavior:
    • draw_rectangle — prints Drawing Rectangle with width: X.XX and height: X.XX (both values shown with 2 decimal places)
    • area_rectangle — returns width × height
    • create_rectangle — initializes a Rectangle, wires up the embedded Shape's function pointers to the rectangle functions, sets the dimensions, and returns the rectangle
  • main.c: Demonstrate both shapes working through the same interface. Read two inputs: width and height for a rectangle. Create a rectangle using your constructor, then call both draw and area through the embedded Shape's function pointers. Print the area with 2 decimal places.

Your program will receive two inputs: width and height values (as floating-point numbers).

Example output when the inputs are 4.0 and 3.0:

Drawing Rectangle with width: 4.00 and height: 3.00
Area: 12.00

Example output when the inputs are 7.5 and 2.5:

Drawing Rectangle with width: 7.50 and height: 2.50
Area: 18.75

Just like with Circle, the Rectangle embeds Shape as its first member, allowing you to access the function pointers through the embedded member. This consistent pattern is what enables polymorphism — both shapes can be treated uniformly through their Shape interface. Remember to use include guards in all header files.

Try it yourself

#include <stdio.h>
#include "shape.h"
#include "rectangle.h"

int main() {
    double width, height;
    scanf("%lf", &width);
    scanf("%lf", &height);
    
    // TODO: Create a rectangle using create_rectangle(width, height)
    
    // TODO: Call draw through the embedded Shape's function pointer
    
    // TODO: Call area through the embedded Shape's function pointer
    // TODO: Print the area with 2 decimal places: "Area: %.2f\n"
    
    return 0;
}

All lessons in Object Oriented Programming