How to write a C++ class in terms of the file structure

by stink on Jan 7, 2025 to cplusplus comments(0)
I am building a text adventure game with C++ in order to relearn the language. So far, I've got everything in a single file, so I was wondering how to split up my classes/structs into their own files. The way it's usually done is to put the class/struct declaration in a header file, let's call it Cat.h:

#ifndef CAT_H
#define CAT_H

struct Cat {
    void meow();
};

#endif

And then you implement meow() in Cat.cpp:

#include "Cat.h"
#include <iostream>

void Cat::meow() {
    std::cout << "meow" << std::endl;
}

Then in main.cpp you can call meow():

#include "Cat.h"

int main() {
    Cat cat;
    cat.meow();
}

To compile this you can run:

g++ main.cpp Cat.cpp
no comments yet