Menu
Coddy logo textTech

Implementation of Account

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

challenge icon

Challenge

Easy

Now 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 opaque Account type declaration and function prototypes for create_account and destroy_account. Keep your include guards with ACCOUNT_H.
  • account.c: This is where the magic happens. Define the actual struct Account with two hidden members: int id (the account identifier) and double 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 destroyed

Where 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