Menu
Coddy logo textTech

Circle Implementation

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

challenge icon

Challenge

Easy

Let's continue building the Shape Drawer project by implementing the Circle — a concrete shape that embeds the base Shape struct and provides its own drawing and area logic.

Building on the foundation from the previous lesson, you'll extend your project with these files:

  • shape.h: Keep your base Shape interface from the previous lesson with the DrawFunc and AreaFunc function pointer types.
  • circle.h: Define your Circle struct here. A circle embeds Shape as its first member (enabling the first member rule for upcasting) and adds a radius field of type double. Declare a constructor function create_circle that takes a radius and returns a Circle by value.
  • circle.c: Implement the circle-specific behavior here:
    • draw_circle — prints Drawing Circle with radius: X.XX (radius shown with 2 decimal places)
    • area_circle — returns π × radius² (use 3.14159 for π)
    • create_circle — initializes a Circle, wires up the embedded Shape's function pointers to point to draw_circle and area_circle, sets the radius, and returns the circle
  • main.c: Bring everything together. Read a radius value as input, create a circle 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 one input: a radius value (as a floating-point number).

Example output when the input is 5.0:

Drawing Circle with radius: 5.00
Area: 78.54

Example output when the input is 3.5:

Drawing Circle with radius: 3.50
Area: 38.48

The key insight is that Circle contains a Shape as its first member, so you can access the function pointers through circle.base.draw and circle.base.area (or whatever you name the embedded member). When calling these functions, pass a pointer to the Shape member. Remember to use include guards in all header files.

Try it yourself

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

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

All lessons in Object Oriented Programming