When do we know that a constructor is required?

I'm not a beginner nor a professional in C++ programming.I'm with the basics.I know how to create a constructor & its types.
My question is-
1.When do we use a constructor?
(Please explain me in a layman language.)
I mean in an industry when they build a software,at what point do they require constructors?
2.Is there any alternative to constructors?
3.Why is it given such high importance?
Last edited on
A constructor is required when have to initialize variables. So pretty much always.

If you don't provide a constructor the compiler will generate one for you anyway
As coder said, when you create an instance of a class, you use a constructor. I suppose if you insisted on not using one, you could allocate some memory yourself and then do some kind of horrific pointer manipulation and some savage type-casting, but that'd be far more effort than just using the constructor.

It's given high importance because you use one every time you create an instance of a class; making good constructors can make creating the instances much easier.
...and also every time you make an instance of a primitive type. For example:
1
2
3
4
5
6
7
8
9
10
int main()
{
	char *a = new char; //Who knows what value the character has?
	char *b = new char (); //The character is guaranteed to have a value of 0
	cout << short(*a) << ' ' << short(*b);
	delete a;
	delete b;
	cin.sync();
	cin.ignore();
}
This can also be used with new[]

For some reason I cannot do char b (); without getting linker errors about unresolved externals - I'll figure that one out later >_>
Last edited on
I use a constructor to make an object valid. By 'valid' I mean that its internal data contain safe values so that member functions can be called without causing undefined behaviour.

This could involve setting values to zero, setting pointers to zero or make them point at something.

Don't feel you have to completely initialize an object through its constructor but it must be valid. By this I mean that you should not feel the need for a Customer class to take in all the customer's details through the constructor. Simply use the constructor to make the object valid and then use member functions to set the customer's details:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Customer
{
	unsigned long id;
	std::string name;
	std::vector<Address> addresses;
	std::string email;

	Customer* referrer;
	
public:
	Customer(): id(0), referrer(0) {} // ensure that referrer is a VALID pointer
	
	unsigned long get_referrer_id()
	{
		// member function depends on pointer being zero to indicate
		// non-availability
		if(referrer != 0) return referrer->id;
		
		return 0L;
	}
}


Sometimes it can make sense to initialise an object through its constructor. For example a class that represents a coordinate:
1
2
3
4
5
6
7
class Coordinate
{
	double x, y;
	
public:
	Coordinate(double x, double y): x(x), y(y) {} // initialize through constructor
};


So I would say generally speaking that if you have a relatively large number of fields whose values are going to come from either a database or a form that a user has filled in then don't use the constructor to get those values into the object. Use the constructor simply to put a new object into a safe and well defined state.

For objects with a relatively few fields where it makes life more convenient to set their values when you create the object (like with points, complex numbers etc..) then by all means use the constructor for that.
Last edited on
@coder777:
"A constructor is required when have to initialize variables",this is the exact definition in my text book.we also initialize a variable say like:

int x=5;

then what makes a constructor different?
closed account (zb0S216C)
Sidmetal98 wrote:
then what makes a constructor different? (sic)

Constructors are automatically invoked and they have the same identifier as the class. Other than the latter, there's not much difference (compared to methods).

Wazzak
Last edited on
Type s = t; calls the appropriate constructor, or copy constructor if t is a Type. All classes have a constructor. As coder777 said, if you don't explicitly define one, the compile will generate a default constructor for you that takes no arguments and does nothing.

Sidmetal98 wrote:
Is there any alternative to constructors?
Yes. Static methods.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Object {
 private:
   /**
    * By defining the constructor as private, we hide it from the rest of the program.
    * Now this class can not be instantiated anywhere except in the methods of this class (and its friends.)
    */
   Object() {}

 public:
   /**
    * We can however create a public static method that calls our private constructor,
    * and then returns an instance of this class.
    */
   static Object makeObject() { return Object; }
};

int main() {
   Object o; //Error!
   Object j = Object::makeObject(); //copy the return value from makeObject() to j.
   //NOTE: The above line is okay because the default copy constructor is public.
   return 0;
}
Last edited on
Topic archived. No new replies allowed.