Click here to Skip to main content
15,880,967 members
Articles / Programming Languages / C
Article

Explicit Constructor in C++

Rate me:
Please Sign up or sign in to vote.
4.67/5 (120 votes)
18 Aug 2008CPOL2 min read 180.6K   270   45   27
Explicit constructor in C++.

Introduction

A constructor really makes your class simple and elegant. Constructors are such basic foundation for your code that a compiler provides it for you, by default. This is called as the default constructor. That is, in C++, if you write just a single line of code:

Class A{ };

the compiler provides you a default zero argument constructor, along with a destructor, a copy constructor, and a copy assignment operator.

Background

So, what is an Explicit Constructor?

In order to understand explicit construction, we need to understand implicit conversion first, and let’s see how it helps you while writing code, and sometimes how this feature is not desirable.

Using the code

Example 1: Consider the following traditional, simple, complex number class:

#include <iostream>
using std::cout;
using std::endl;
class complexNumbers {
  double real, img;
public:
  complexNumbers() : real(0), img(0) { }
  complexNumbers(const complexNumbers& c) { real = c.real; img = c.img; }
  complexNumbers( double r, double i = 0.0) { real = r; img = i; }
  friend void display(complexNumbers cx);
};
void display(complexNumbers cx){
  cout<<&quot;Real Part: &quot;<<cx.real<<&quot; Imag Part: &quot;<<cx.img<<endl;
}
int main() {
  complexNumbers one(1);
  complexNumbers five = 5;
  display(one);
  display(five);
  return 0;
}

The class complexNumbers is really simple; it contains two parts named real and img for a complex number’s real and imaginary parts. The code defines a default constructor, a copy constructor, and most importantly, defines another constructor which helps us to do implicit construction.

In main, we first create an object of the class named “one”, and then another named “five”, both of these calls succeed because of the implicit conversation happening beneath. So, for the object “one”, the “real” part of the object becomes 1, and the “img” part becomes 0, and for the object “five”, the “real” part becomes 5 and the “img” part becomes 0. Then, we print that complex number using a method named “display”. Nice example indeed, and as of now, implicit conversion rocks. Given below is the output:

Real Part: 1 Imag Part: 0
Real Part: 5 Imag Part: 0

Now, consider this one:

#include <iostream>
using std::cout;
using std::endl;
class complexNumbers {
  double real, img;
public:
  complexNumbers() : real(0), img(0) { }
  complexNumbers(const complexNumbers& c) { real = c.real; img = c.img; }
  complexNumbers( double r, double i = 0.0) { real = r; img = i; }
  friend void display(complexNumbers cx);
};
void display(complexNumbers cx){
  cout<<&quot;Real Part: &quot;<<cx.real<<&quot; Imag Part: &quot;<<cx.img<<endl;
}
int main() {
  complexNumbers one(1);
  display(one);
  display(300);
  return 0;
}

A similar example, just added one more line in main ===> display(300);. And, here we go, the output becomes:

Real Part: 1 Imag Part: 0
Real Part: 300 Imag Part: 0

Bang!!! That was really not expected. First, the code is itself confusing, what does display(300) mean? 300 itself is never an object/instance of the class complexNumbers that the method display expects as an argument. So, how does this happen?

Since the method display expects an object/instance of the class complexNumbers as the argument, when we pass a decimal value of 300, an implicit conversion happens in-place, which in-turn transfers the decimal value of 300 to a temporary object of class complexNumbers (and thereby assigns the value 300 to the real part of that temporary object).

How doe we overcome this situation??

Simple, force the compiler to create an object using explicit construction only, as given below:

#include <iostream>
using std::cout;
using std::endl;
class complexNumbers {
  double real, img;
public:
  complexNumbers() : real(0), img(0) { }
  complexNumbers(const complexNumbers& c) { real = c.real; img = c.img; }
  explicit complexNumbers( double r, double i = 0.0) { real = r; img = i; }
  friend void display(complexNumbers cx);
};
void display(complexNumbers cx){
  cout<<&quot;Real Part: &quot;<<cx.real<<&quot; Imag Part: &quot;<<cx.img<<endl;
}
int main() {
  complexNumbers one(1);
  display(one);
  complexNumbers two =2;
  display(200);
  return 0;
}

Consider the following statement:

explicit complexNumbers( double r, double i = 0.0) { real = r; img = i; }

Here, we are forcing the compiler not to do an implicit conversion for this piece of code. Now, if the programmer puts a line containing an implicit conversation, the compiler returns back with an error:

bash-3.2$ g++ -g -o hello test2.cpp 
test2.cpp: In function ‘int main()’:
test2.cpp:22: error: conversion from ‘int’ to non-scalar type ‘complexNumbers’ requested
test2.cpp:23: error: conversion from ‘int’ to non-scalar type ‘complexNumbers’ requested

From this point onwards, the programmers need to use this:

display(complexNumbers(200)); //only explicit conversion is allowed…………

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Rebaca Technologies
India India
int main(){
while(!isSleeping())
{
write_code();
}
return 0;
}

Comments and Discussions

 
Questionimplicit call Pin
Gerhard Biebl3-Aug-16 21:29
Gerhard Biebl3-Aug-16 21:29 
Questionshould be a more simple explanation Pin
shiftwik25-Feb-15 7:31
shiftwik25-Feb-15 7:31 
GeneralMy vote of 5 Pin
Anton Kaminsky28-Aug-14 19:36
Anton Kaminsky28-Aug-14 19:36 
QuestionThank you! Pin
Nishan Lakmal Satharsinghe20-May-13 23:17
Nishan Lakmal Satharsinghe20-May-13 23:17 
QuestionGood Pin
RS.Ratheesh22-Nov-12 23:20
RS.Ratheesh22-Nov-12 23:20 
GeneralMy vote of 5 Pin
gsanthosh9-Oct-12 22:22
gsanthosh9-Oct-12 22:22 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey28-Feb-12 18:00
professionalManoj Kumar Choubey28-Feb-12 18:00 
GeneralMy vote of 5 Pin
Rahul Rajat Singh16-Feb-12 1:17
professionalRahul Rajat Singh16-Feb-12 1:17 
GeneralDamn simple explanation Pin
san_to_all16-Oct-11 4:34
san_to_all16-Oct-11 4:34 
GeneralNeeds an example where explicit solves a bug (vote of 4) Pin
jean Davy19-Dec-10 23:51
jean Davy19-Dec-10 23:51 
GeneralRe: Needs an example where explicit solves a bug (vote of 4) Pin
mike17315-Aug-13 23:19
mike17315-Aug-13 23:19 
GeneralMy vote of 3 Pin
Omkar Somani16-Dec-10 19:19
Omkar Somani16-Dec-10 19:19 
Generalgood job Pin
Mehmet Suyuti Dindar10-Jan-10 23:02
Mehmet Suyuti Dindar10-Jan-10 23:02 
GeneralFive again Pin
Akram Ben Hassan1-Dec-09 23:18
Akram Ben Hassan1-Dec-09 23:18 
I wish you continue this series of simplifying c++ for beginners.
GeneralMeaning [modified] Pin
Anil Srivastava13-Sep-09 22:14
Anil Srivastava13-Sep-09 22:14 
GeneralRe: Meaning Pin
programmersmind16-Sep-09 16:37
programmersmind16-Sep-09 16:37 
GeneralHello Pin
Anil Srivastava22-Sep-09 0:25
Anil Srivastava22-Sep-09 0:25 
GeneralRe: Hello Pin
Like2Byte30-Nov-09 16:56
Like2Byte30-Nov-09 16:56 
GeneralGood explanation Pin
akirilov9-Sep-08 23:24
akirilov9-Sep-08 23:24 
General... or follow Google coding conventions Pin
Cristian Amarie5-Sep-08 8:25
Cristian Amarie5-Sep-08 8:25 
GeneralRe: ... or follow Google coding conventions Pin
programmersmind25-Aug-09 3:19
programmersmind25-Aug-09 3:19 
Generalsuggestion Pin
Emilio Garavaglia20-Aug-08 6:11
Emilio Garavaglia20-Aug-08 6:11 
GeneralRe: suggestion Pin
Stefan_Lang25-Aug-08 21:54
Stefan_Lang25-Aug-08 21:54 
GeneralRe: suggestion Pin
Emilio Garavaglia25-Aug-08 22:54
Emilio Garavaglia25-Aug-08 22:54 
GeneralThanks for this - very useful to know Pin
Mike Diack18-Aug-08 21:40
Mike Diack18-Aug-08 21:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.