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

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)

Abstract class

 If we can not create any objects of a class, then it is called an abstract class. A class is made abstract by adding at least one pure virtual function to it. Pure virtual function A function is said to be a pure virtual function , if it has no definition but has only declaration. Pure virtual function is defined with the keyword virtual and followed by return type, function name and "=0". class Shape { public: virtual void printarea() =0 ; }; int main () { Shape obj1; //error } Here printarea() function of Shape class is a pure virtual function as it has no body. To make a function as pure virtual function, you should use =0 at the end of virtual function declaration Abstract class When a class has at least one pure virtual function, it is incomplete and no objects can be created from that class. Such a class is called an abstract class . In the earlier example class Shape is an abstract class, and objects can not be created from t...

Friends of C++

Friend function Remember that a member which is not public (Private and protected )  can not be accessed from outside the class.  Three are some situations where you may need to access these. Keyword friend  is used for this. A friend functions and classes can access all members of a class.  This concept is controversial. People say friend concept violates data encapsulation  A friend function is a non-member function but still can access all the members of a class including private members. Such a function is declared within class body with the prefix "friend" class Number { int num; public: Number( int m){ /*code*/ } friend void printNum(Number ob); /*friend function*/ }; void printNum (Number obj) { cout << obj.num << "endl" ; } printNum() is not member of class Number . But it can still access all members including private members, because it is a friend. Friend class An object of a friend c...