I have an application that has classes and functions all within the source file. I've been reading on how to place them into dedicated .cpp & .h files. However, I've noticed that the .h file will only include the definitions and the .cpp file only contains the implementation of the functions and not the data members.
My question is if I want to have classes in separate files, which of the two would the variables of a function be defined in?
Here is some code information:
Class:
class Post { //Will hold the contents of a single post.
private:
int UserID;
std::string message;
//time_t date; // Will eventually hold a time value.
public:
static void postMenu(User& currentUser, bool loggedIn) {
std::cout << "\n**********************************\n POST MENU\n**********************************\n\n";
char postChoice = ' ';
std::cout << "\n[P] - Post to board.\n[V] - View Board.\n[E] - Exit to main menu.\n\n>";
std::cin >> postChoice;
postChoice = toupper(postChoice);
if (postChoice == 'P') {
Post currentUserPost;//Initilize current post.
currentUserPost.loadPosts();
currentUserPost.postMessage(currentUser, loggedIn);
currentUserPost.loadPosts();
//PlaySound(TEXT("C:/Users/19097/Desktop/Programs/Registration Application/App files/Audio/ding.wav"), NULL, SND_FILENAME | SND_ASYNC); // Sound when message is posted
}
else if (postChoice == 'V') {
Post::loadPosts(); //Loads the post wall for viewing
}
else if (postChoice == 'E') {
std::cout << "\nExiting..." << std::endl;
return;
}
}
char postMessage(User& currentUser, bool loggedIn) { //Will post a message to the board. Passes a User object.
if (loggedIn == false) {
std::cout << "You must be logged in to post!" << std::endl;
User::userLoginRegisterPrompt();
return 'F';
}
std::string message; //Actual message string
std::cout << "\nEnter your message: ";
std::cin.ignore(); //Clears string buffer.
getline(std::cin, message);
std::ofstream post("App files/UserPosts/-Posts.txt", std::ios::app); //File with user posts.
post << currentUser.getUserName() << ": " << message << std::endl;
post.close();
logAction(currentUser.getUserName(), "Made a post");
}
static bool loadPosts() { //Will be for viewing the post history.
std::ifstream post("App files/UserPosts/-Posts.txt");
std::string line;
if (!post) {
std::cout << "No board exists!" << std::endl;
return false;
}
std::cout << "\n**********************************\n GLOBAL POST\n**********************************\n\n";
while (getline(post, line)) {
std::cout << line << std::endl;
}
std::cout << "\n\n**********************************\n**********************************\n\n";
}
};
How would the .cpp and .h files for this class look? I saw an example where the declarations were declared within the .h file and all the function bodies were left in the .cpp file.
However, they stated that all data members and class/static keywords should be removed from .cpp file.
This is the tutorial for reference: https://www.youtube.com/watch?v=nbd7o8iKh9Q&ab_channel=CalebCurry