Click here to Skip to main content
11,638,881 members (71,977 online)
Click here to Skip to main content

Explicit Constructor in C++

, 18 Aug 2008 CPOL 86.6K 158 45
Rate this:
Please Sign up or sign in to vote.
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 <span class="code-keyword"><iostream></span>
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 <span class="code-keyword"><iostream></span>
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 <span class="code-keyword"><iostream></span>
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)

Share

About the Author

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

You may also be interested in...

Comments and Discussions

 
Questionshould be a more simple explanation Pin
shiftwik25-Feb-15 7:31
membershiftwik25-Feb-15 7:31 
GeneralMy vote of 5 Pin
Anton Kaminsky28-Aug-14 19:36
memberAnton Kaminsky28-Aug-14 19:36 
QuestionThank you! Pin
Nishan Lakmal Satharsinghe20-May-13 23:17
memberNishan Lakmal Satharsinghe20-May-13 23:17 
QuestionGood Pin
RS.Ratheesh22-Nov-12 23:20
memberRS.Ratheesh22-Nov-12 23:20 
GeneralMy vote of 5 Pin
gsanthosh9-Oct-12 22:22
membergsanthosh9-Oct-12 22:22 
GeneralMy vote of 5 Pin
manoj kumar choubey28-Feb-12 18:00
membermanoj kumar choubey28-Feb-12 18:00 
GeneralMy vote of 5 Pin
Rahul Rajat Singh16-Feb-12 1:17
memberRahul Rajat Singh16-Feb-12 1:17 
GeneralDamn simple explanation Pin
san_to_all16-Oct-11 4:34
membersan_to_all16-Oct-11 4:34 
GeneralNeeds an example where explicit solves a bug (vote of 4) Pin
jean Davy19-Dec-10 23:51
memberjean Davy19-Dec-10 23:51 
GeneralRe: Needs an example where explicit solves a bug (vote of 4) Pin
mike17315-Aug-13 23:19
membermike17315-Aug-13 23:19 
GeneralMy vote of 3 Pin
Omkar Somani16-Dec-10 19:19
memberOmkar Somani16-Dec-10 19:19 
Generalgood job Pin
Mehmet Suyuti Dindar10-Jan-10 23:02
memberMehmet Suyuti Dindar10-Jan-10 23:02 
GeneralFive again Pin
Akram Ben Hassan1-Dec-09 23:18
memberAkram Ben Hassan1-Dec-09 23:18 
GeneralMeaning [modified] Pin
Anil Srivastava13-Sep-09 22:14
memberAnil Srivastava13-Sep-09 22:14 
GeneralRe: Meaning Pin
programmersmind16-Sep-09 16:37
groupprogrammersmind16-Sep-09 16:37 
GeneralHello Pin
Anil Srivastava22-Sep-09 0:25
memberAnil Srivastava22-Sep-09 0:25 
GeneralRe: Hello Pin
Like2Byte30-Nov-09 16:56
memberLike2Byte30-Nov-09 16:56 
GeneralGood explanation Pin
akirilov9-Sep-08 23:24
memberakirilov9-Sep-08 23:24 
General... or follow Google coding conventions Pin
Cristian Amarie5-Sep-08 8:25
memberCristian Amarie5-Sep-08 8:25 
GeneralRe: ... or follow Google coding conventions Pin
programmersmind25-Aug-09 3:19
groupprogrammersmind25-Aug-09 3:19 
Generalsuggestion Pin
emilio_grv20-Aug-08 6:11
memberemilio_grv20-Aug-08 6:11 
GeneralRe: suggestion Pin
Stefan6325-Aug-08 21:54
memberStefan6325-Aug-08 21:54 
GeneralRe: suggestion Pin
emilio_grv25-Aug-08 22:54
memberemilio_grv25-Aug-08 22:54 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150728.1 | Last Updated 18 Aug 2008
Article Copyright 2008 by programmersmind
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid