Menu
Coddy logo textTech

Recap: Shape Hierarchy

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

challenge icon

Challenge

Easy

Let's build a complete shape hierarchy that demonstrates the power of inheritance via composition. You'll create a base Shape type that any specific shape can inherit from, then build a Rect that extends it.

You'll organize your code across three files:

  • shape.h: Define your struct hierarchy with include guards. Create a Shape struct with a single color field (an integer). Then define a Rect struct that embeds Shape as its first member and adds width and height fields (both integers). Declare two functions: set_color that takes a Shape* and a new color value, and print_rect that takes a Rect*.
  • shape.c: Implement both functions. Your set_color function works with the base type—it modifies the color of any shape. Your print_rect function displays all the rectangle's information including its inherited color.
  • main.c: Create a Rect and initialize all its fields. Then demonstrate upcasting by calling set_color with your rectangle cast to a Shape*. Finally, print the rectangle to verify the color was changed through the base type pointer.

You will receive four inputs: the rectangle's width, its height, an initial color, and a new color to set via the generic function.

In your main file, create the rectangle with the initial values, then use set_color to change its color to the new value (remember to cast your Rect* to Shape*), and finally call print_rect to display the result.

Your output should look like this:

Width: 10
Height: 5
Color: 7

Where 10 is the width, 5 is the height, and 7 is the updated color (not the initial color). The key insight here is that set_color knows nothing about rectangles—it only works with Shape. Yet through the first member rule and upcasting, your rectangle's color gets modified through this generic function.

Try it yourself

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

int main() {
    int width, height, initial_color, new_color;
    scanf("%d", &width);
    scanf("%d", &height);
    scanf("%d", &initial_color);
    scanf("%d", &new_color);
    
    // TODO: Create a Rect and initialize all its fields
    // (width, height, and the embedded Shape's color with initial_color)
    
    // TODO: Call set_color with the rectangle cast to Shape*
    // to change the color to new_color
    
    // TODO: Call print_rect to display the result
    
    return 0;
}

All lessons in Object Oriented Programming