Dive Deep into CPP : Constructors

You can use constructor with initialization list in addition to the default ways. You cant use initialization list with arrays,list, vector etc. Also static variables cant be initialized using this method. Initialization of reference variable and const variable can only be done through initialization list. It cant be done through constructor body. Body of the constructor believes that the variables have been initialized and so it assigns. Initialization is the first assignment. const and reference variables can be initialized only once. So it must be initialized through initialization list. Static members do not belong to one object of that class. So it cant be initialized through initialization list. But can be done through body, because it only assigns.

A(): x(0),y(0)

Constructor is overloaded using initialization list  like

A(int x_=0) : x(x_)

Class with private constructor cannot be inherited. It can be instantiated by friends of the class or through a public static function.Classes with protected constructors cannot be instantiated outside. Can only be used in inheritance. It will be like abstract base class when virtual functions are not feasible. Base class can be instantiated from outside by using copy constructor. Because it is provided by default by the compiler. So it is partial abstract class. If you want to make it as pure abstract class, make all constructor as protected.
To set a field read only, use constructor to initialize the variable and remove the setter function.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s