Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language:
Expertise: Beginner
Sep 9, 2003

Explicit Constructors

A constructor that takes a single argument is, by default, an implicit conversion operator, which converts its argument to an object of its class, the keyword "explicit" can be placed before the constructor with one parameter to avoid such implicit conversions.

Sample Code:


#include <iostream.h>

class test
{
   int i;
   int j;
public:
   test()
   {
      i=100;
      j=200;
   }

   explicit test(int x)
   {
      i=x;
      j=x+10;
   }

   void disp()
   {
      cout<<"I="<<i<<endl;
      cout<<"J="<<j<<endl<<endl;
   }
};

int main()
{
   test m1;
   test m2(10);
   test m3;

   m3=500;  //Compiler will complain, because the
			//one argument constructor has been made explicit.

   m1.disp();
   m2.disp();
   m3.disp();

   return(1);
}
Rajashekar Narla
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date