Implementation of Account
Part of the Object Oriented Programming section of Coddy's C journey — lesson 23 of 61.
Challenge
EasyNow it's time to bring your Bank Account to life! You've already created the public interface in account.h—now you'll implement the hidden internals that make it work.
Building on your previous work, you'll add the source file that contains the secret struct definition and the actual function implementations. This is where encapsulation truly happens—the struct body exists only in the .c file, completely invisible to anyone using your library.
You'll work with three files:
account.h: Your existing header with the opaqueAccounttype declaration and function prototypes forcreate_accountanddestroy_account. Keep your include guards withACCOUNT_H.account.c: This is where the magic happens. Define the actualstruct Accountwith two hidden members:int id(the account identifier) anddouble balance(starting at 0.0 for new accounts). Implement your constructor to allocate memory, set the ID from the parameter, and initialize the balance to zero. Implement your destructor to properly free the memory.main.c: Test your implementation by creating an account and confirming it works. Since the struct members are hidden, you can't peek inside—but you can verify the lifecycle works correctly.
You will receive one input: the account ID (an integer) to assign to the new account.
In your main file, create an account with the provided ID, print a confirmation message showing the ID, then destroy the account and confirm cleanup.
Print the output in this format:
Account 1001 created
Account destroyedWhere 1001 is replaced with the actual ID you received as input.
Remember: your main.c cannot access account->id or account->balance directly—those members are completely hidden inside account.c. For now, you'll just use the ID from the input for your output message. In upcoming lessons, you'll add getter functions to retrieve the hidden data properly.
Try it yourself
#include <stdio.h>
#include "account.h"
int main() {
int account_id;
// TODO: read account_id from input
scanf("%d", &account_id);
// TODO: create an account using create_account() and print "Account <id> created"
// TODO: destroy the account using destroy_account() and print "Account destroyed"
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