An object (instance of a class) is like a record (or struct) or a collection of data members (variables).
Example:
1 2 3 4 5 6 7 8 9 10
|
#include <string>
using namespace std;
class Customer
{
private:
string m_name;
string m_address;
char m_gender; // 'M' or 'F'
};
|
The C++ compiler will automatically generate a Customer::Customer() default constructor for you, but this constructor will do nothing for you.
1 2 3 4
|
main()
{
Customer customer1;
}
|
You've just declared a customer1, but and customer1.m_gender can actually contain anything because the default constructor does no initialization of raw data for you (and will call default constructors on data members which are objects eg m_name, m_address). Is this what you really want? Most likely not.
You have a few choices:
1. Write your own Customer::Customer() which will initialize your data members to something - actually, those strings will call default constructors and initialize to "", but m_gender will be random.
2. Write your own Customer::Customer( const string& name, const char& address, char gender )
The latter choice is even better because you can ensure that the user has initiated your instance with real data, and it will disable the auto-generation of the default constructor by the compiler (you need to write your own).
Later, when you dynamically allocated memory (using new and delete), you will almost always want to write a default constructor, a destructor, an assignment operator, and a copy operator. Or at least disable the automatic generation of some or all of the above.
EDIT: correction made to initialization by default constructors