Skip to main content

Constructors - Part II

Single Parameter Constructor

If a class has a constructor with one parameter, then assignment statement uses this constructor to convert variable of this type  into the object of the class. 


class A
{
public:
 A(int m)
 {
 cout<<"constructor "<<endl;
 }
};
 
int main()
{
 A obj1(3); 
 int m = 100;
 obj1 = m;
}


Output:
constructor constructor

Here obj1 =m is calling the constructor with one int parameter. That is to say, the constructor is working as conversion operator.

If you do not want assignment to call such a constructor, you can specify keyword explicit before constructor.  
class A
{
public:
 explicit A(int m)
 {
 cout<<"constructor "<<endl;
 }
};
 
int main()
{
 A obj1(3); 
 int m = 100;
 obj1 = m;/*error*/
}

In the code above, the constructor is defined as explicit. So it can not be used for implicit conversion. So obj1=m can not use constructor and gives a compiler error.

Private Constructor

A constructor is always made public because user must be able to access it to initialize an object. But what if we make the constructor private? What if there is only one private constructor to the class ?

Objects can still be created using such classes using some tweaks. These class  must have  static public method which creates  objects and returns them.


#include <iostream>
using namespace std; 
class A
{
 int m;
 A(int n);/*private ctor*/
 static A * instance;
public:
 static A* getInstance(int m);
 int getm()
 {
 return m;
 }
};
A* A::instance=0;
A::A(int n):m(n)
{ 
}
A* A::getInstance(int m)
{
 if(instance == 0)
 {
 instance = new A(m);
 } 
 return instance;
}
int main()
{
 A *aptr = A::getInstance(10);
 cout<<aptr->getm();
 A *anotherptr = A::getInstance(20);
 cout<<anotherptr->getm();
}


Here getInstance() calls private constructor if needed and then returns the pointer to  object of class A. Also note that, the above class allows only one object to be created from the class ( such classes are called singletons)

Array of objects

Array of objects is initialized using default constructor. 
If a class has no default constructor and we try to create an array of objects, then array definition throws an error.


 
class A{
public:
 A(int m){/* code*/}
};
class B
{
 int m;
};
int main()
{
 A obj[10];//error
 B obj2[5];/*no error*/
}


In the above example, class A has only parameterized ctor but  no default constructor. So the array definition obj1[10] throws an error.

No matching call to A::A()

 But for class B, compiler provides a default ctor, as it has no user defined ctor. And array obj2 is created using this compiler provided default ctor.

But we can also use array initializers explicitly for classes with no default constructors in the above example for class A.
class A{
public:
 A(int m){cout<<"ctor"<<m<<"\n";}
};
int main()
{
 A obj[4]={1,12,3,4};/*no error*/
 B obj2[5];/*no error*/
}

Output of the program
ctor1
ctor2
ctor3
ctor4
In the code above, obj array calls parameterized constructor because there is an array initializer list provided. So obj[0] is constructed with parameter 1, obj[1] is constructed with parameter 12 etc.

This initializer can even be used with multiple parameter constructors.
 
class A
{
/*code*/
public:
 A(int m,int n){/*code*/}
};

A arr[4] = {A(1,1),A(3,4),A(5,8),A(11,2)};

Comments

Popular posts from this blog

C quizard app

C Quizard is an app which will make you from newbie in C to C wizard. The app has quiz on various topics, solved programs with explanations. It also lets you take a 25 question quiz any time offline. You can download CQuizard by Hegdeapps from google play.

Find the error in C++ program

This C++ program is not compiling. What do you think is the error with the program? #include<iostream> using namespace std; int main() {    int arr[10];    arr={1,2,3,4,5,6,7,8};    cout<<"arr[0]="<<arr[0];    return 0; } Is the error due to Not using printf Initialising the array with only 8 elements instead of 10 Initialising array in the next statement instead of in definition. None of the above  Now if you like this question, there are plenty more questions like this and programs and notes in my app Simplified C++. Download the Simplif ied C++   by Hegdeapps now By the way the correct answer is (3)

Polymorphism

You hear the term Polymorphism too frequently with object oriented languages. Along with Inheritance and Encapsulation, polymorphism is one of the corner stones of object oriented design. What is Polymorphism, exactly? Polymorphism is a mechanism by which you provide single interface for multiple methods. (poly - many, morph - form). In C++, polymorphism can be compile time or run-time. Compile time polymorphism is provided with the help of overloaded operators/functions and templates. Run time polymorphism is provided with the help of virtual functions and late binding. Late Binding: Connecting a function call to function body is called binding. Most functions use early binding where this binding happens before the program is run - during compile time. This is also called static binding. Late binding (also called dynamic binding)  is when a function call is connected to function body at run time. This is done after looking at the type of the object. Late binding is...