I’m a C++ beginner. I have a class and when I try to compile it says it’s missing ‘main’.
What do I need to do to create an instance of this class and access its methods?
#include <string>
#include <iostream>
using namespace std;
class Account
{
string name;
double balance;
public:
Account(string n);
Account(string n, double initial_balance);
string get_name() const;
double get_balance() const;
void deposit(double amount);
void widthdraw(double amount);
};
edit:
Where do I put the main method?
I have tried putting it in a different file like the following
#include <Account>
int main(){
Account:: Account(string n) : name(n), balance(0){}
return 0 ;
}
but this gives an error saying there is not Account in the directory. I’m guessing this is because it’s not compiled
edit:
Both files are in the same directory
account_main.cc
#include<string>
#include <iostream>
#include "Account.cc"
Account:: Account(string n) : name(n), balance(0){}
int main()
{
Account account("Account Name"); // A variable called "account"
account.deposit(100.00); // Calls the deposit() function on account
return 0 ;
}
Account.cc
#include<string>
#include <iostream>
using namespace std;
class Account
{
string name;
double balance;
public:
Account(string n);
Account(string n, double initial_balance);
string get_name() const;
double get_balance() const;
void deposit(double amount);
void widthdraw(double amount);
};
All C++ programs require what’s called an entry point. The
main()function is always the entry point for standard C++ programs. You need to provide amain(), function otherwise the linker will complain. You can write amain()function in one of two ways:Or, if you are expecting command-line arguments:
Note that
void main()is not valid in C++. Also note that areturnstatement isn’t strictly necessary formain()functions, but you should explicitly write one anyway, for the sake of consistency.To answer your question about your latest edit:
The form of
main()is correct, but this is not how you provide class member definitions. The constructor needs to be outside the main function.To create an instance of
Account, you declare a variable and pass all the required constructor arguments like this:Also, check the exact file path of where
class Accountis. If theAccountclass is in a file calledAccount.hand is in the same folder as the file containing themain()function, then you need to use#include "Account.h"instead of#include <Account>in that file. For example:This is actually a rather fundamental aspect of the C++ programming language. Surely you have a book that covers this? In fact,
main()functions and#includestatements are usually the first thing that you learn when programming in C++. I highly recommend that you pick up a good C++ book and read through them and do the exercises.