Recap: Greeter
Part of the Object Oriented Programming section of Coddy's C journey — lesson 43 of 61.
Challenge
EasyLet'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 calledGreetFuncthat takes aconst char*(a name to greet) and returns nothing. Then define aGreeterstruct containing alanguage(aconst char*) and agreetfunction pointer of typeGreetFunc.greeter.c: Implement the greeting functions that represent different languages:greet_english— printsHello, name!greet_spanish— printsHola, name!
main.c: Bring everything together here. Create twoGreeterinstances — one for English and one for Spanish — each wired to its respective greeting function. Read a name as input, then call thegreetfunction 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
1Modular Programming Basics
Header FilesInclude GuardsSource FilesStatic FunctionsRecap: Modular Calculator4Encapsulation
Opaque Pointers ConceptDefining Opaque StructsGetters and SettersValidation in SettersRecap: Secret Box2Objects and Methods
Structs as ObjectsThe 'Self' PointerConst CorrectnessPointer vs ValueHelper MethodsRecap: Point Manager5Project: Simple Bank Account
Project SetupImplementation of Account3Object Lifecycle
Constructor PatternDestructor PatternStack InitializationDeep CopyRecap: String Wrapper6Inheritance via Composition
Struct EmbeddingThe First Member RuleAccessing Parent MembersUpcastingRecap: Shape Hierarchy