Menu
Coddy logo textTech

Recap: Greeter

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

challenge icon

Challenge

Easy

Let's build a Greeter system that demonstrates polymorphism through function pointers — the same struct type producing different outputs based on which greeting function is wired in.

You'll organize your code across three files:

  • greeter.h: Define your greeter interface here. Create a function pointer type called GreetFunc that takes a const char* (a name to greet) and returns nothing. Then define a Greeter struct containing a language (a const char*) and a greet function pointer of type GreetFunc.
  • greeter.c: Implement the greeting functions that represent different languages:
    • greet_english — prints Hello, name!
    • greet_spanish — prints Hola, name!
  • main.c: Bring everything together here. Create two Greeter instances — one for English and one for Spanish — each wired to its respective greeting function. Read a name as input, then call the greet function on both greeters to demonstrate polymorphic behavior.

Your program will receive a single input: a name to greet.

Create an English greeter with language set to English and a Spanish greeter with language set to Spanish. For each greeter, print its language followed by a colon and space, then call its greet function with the input name.

Example output when the input is Maria:

English: Hello, Maria!
Spanish: Hola, Maria!

Example output when the input is Carlos:

English: Hello, Carlos!
Spanish: Hola, Carlos!

Both greeters are the same Greeter type, yet they produce different greetings because each has a different function assigned to its greet member. Remember to use include guards in your header file.

Try it yourself

#include <stdio.h>
#include <string.h>
#include "greeter.h"

int main() {
    // Read the name input
    char name[100];
    scanf("%s", name);
    
    // TODO: Create an English greeter
    // - Set language to "English"
    // - Set greet to greet_english function
    
    
    // TODO: Create a Spanish greeter
    // - Set language to "Spanish"
    // - Set greet to greet_spanish function
    
    
    // TODO: For each greeter:
    // 1. Print the language followed by ": "
    // 2. Call the greet function with the name
    
    
    return 0;
}

All lessons in Object Oriented Programming