constructors (classes)

hello,

I read the tutorial about classes and I did not quiet understand the purpose of using constructors (default or with parameters), I dont know why do we need it? and what is its purpose? it seems like a big deal to use them with classes.

someone please explain to me very slowly how this work. thanks c++
The main use is to establish the class invariants (basically guarantees that the class wants to provide). For example, std::string's default constructor will construct an empty string, allocate memory, set it's internal size variable, etc.
I dont get it
A constructor basically sets up your class for use by you. When you create a new function, the constructor (usually) initializes your variables which previously had nothing in them (save garbage left over from the last function) to mean something. Different constructors set up these variables differently. Does this help?

-Albatross
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
Last edited on
Topic archived. No new replies allowed.