-5

I don't understand the purpose of constructors and how they function in C++. I understand that a constructor a is a function within a class that has the same name as the class but does not have a return type.

user3386053
  • 13
  • 1
  • 4
  • Do you like being able to initialize `int` variables to a value (e.g., `int i = 2;`)? Good. Now, would you like being able to initialize objects of non-primitive types the same way? It (generally) needs a constructor. – chris Mar 14 '14 at 02:06
  • [google c++ constructor tutorial](http://www.learncpp.com/cpp-tutorial/85-constructors/) happy reading; or you could pick up just about any intro c++ book – jpw Mar 14 '14 at 02:07
  • What you need is a basic C++ book. Maybe [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?rq=1) can help you. – songyuanyao Mar 14 '14 at 02:07

1 Answers1

2

The purpose of a constructor in C++ is to reliably initialize raw memory, turning it into a useful object by establishing the chosen class invariant (what you can always assume about the object between calls of its member functions).

In contrast, an assignment has to change the value of an already initialized object, and may for example have to deallocate buffers that already have been established.

As long as you don't use very low level features of the language there is effectively a constructor call guarantee: that every object instantiated from a type T that has at least one user defined constructor, gets a single external call to a T constructor, which happens before anything else. Conversely, when you call a constructor by using the type name as a pseudo function name, T(), or with arguments, a T object is created. So the guarantee works both ways, and means that object creation involves constructor call and vice versa.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331