GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 09-Jun-2008, 02:19
Archer Archer is offline
Junior Member
 
Join Date: May 2008
Posts: 31
Archer is on a distinguished road

Question related to Operator overloading


i want to know the use about declaring a constructor as explicit??
what are its advantages or disadvantages??
  #2  
Old 09-Jun-2008, 02:40
Archer Archer is offline
Junior Member
 
Join Date: May 2008
Posts: 31
Archer is on a distinguished road

Re: Question related to Operator overloading


Sorry the subject of this topic may be misleading i read this in operator overloading:
Code is here:

CPP / C++ / C Code:

CPP / C++ / C Code:
// englplus.cpp
// overloaded '+' operator adds two Distances
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Distance                    //English Distance class
   {
   private:
      int feet;
      float inches;
   public:                        //constructor (no args)
      Distance() : feet(0), inches(0.0)
         {  }                     //constructor (two args)
  Distance(int ft, float in) : feet(ft), inches(in) 
         {  }
      void getdist()              //get length from user
         {
         cout << "\nEnter feet: ";  cin >> feet;
         cout << "Enter inches: ";  cin >> inches;
         }
      void showdist() const       //display distance
         { cout << feet << "\'-" << inches << '\"'; }

      Distance operator + ( Distance ) const;  //add 2 distances
   };
//--------------------------------------------------------------
                                  //add this distance to d2
Distance Distance::operator + (Distance d2) const  //return sum
   {
   int f = feet + d2.feet;        //add the feet
   float i = inches + d2.inches;  //add the inches
   if(i >= 12.0)                  //if total exceeds 12.0,
      {                           //then decrease inches
      i -= 12.0;                  //by 12.0 and
      f++;                        //increase feet by 1
      }                           //return a temporary Distance
   return Distance(f,i);          //initialized to sum
   }
////////////////////////////////////////////////////////////////
int main()
   {
   Distance dist1, dist3, dist4;   //define distances
   dist1.getdist();                //get dist1 from user

   Distance dist2(11, 6.25);       //define, initialize dist2
   Distance dist5=11.35;
   dist3 = dist1 + dist2;          //single '+' operator

   dist4 = dist1 + dist2 + dist3;  //multiple '+' operators
                                   //display all lengths
   cout << "dist1 = ";  dist1.showdist(); cout << endl;
   cout << "dist2 = ";  dist2.showdist(); cout << endl;
   cout << "dist3 = ";  dist3.showdist(); cout << endl;
   cout << "dist4 = ";  dist4.showdist(); cout << endl;
   return 0;
   system("pause");
   }
/CPP / C++ / C Code:

Now i has 3 observation regarding this code.

1. This code works perfectly with or without keyword explicit.
Now if i change a statement
dist3 = dist1 + dist2; to
dist3 = dist1 + 12.25; Code stops work .But if initialize 2 argument constr as
Distance(int ft, float in=0.0) : feet(ft), inches(in)
{ }
This code works.

2.Using explicit keyword makes the code stop compiling.That ok.

3.when i am not using 'explicit', conversion are happening but results are not as desired, because of possible initialization of inches always to 0.0.
So what is use of keyword explicit??
Last edited by admin : 09-Jun-2008 at 04:12. Reason: Please insert your example C/C++ codes between [CPP] and [/CPP] tags
  #3  
Old 09-Jun-2008, 05:01
ocicat ocicat is offline
Regular Member
 
Join Date: May 2008
Posts: 580
ocicat is a jewel in the roughocicat is a jewel in the rough

Re: Question related to Operator overloading


Quote:
Originally Posted by Archer
Code is here:
When posting code, please bracket it with [cpp] before & [/cpp] as this standardizes presentation & preserves formating.

Quote:
This code works perfectly with or without keyword explicit.
Actually, this is surprising given the line:
CPP / C++ / C Code:
Distance dist5=11.35;
...because the code as presented above should not compile. No constructor is defined which takes only a single argument. I suspect you had already defaulted the constructor's second argument, but didn't post this code.
Quote:
dist3 = dist1 + 12.25; Code stops work .But if intialize 2 argument constr as
Distance(int ft, float in=0.0) : feet(ft), inches(in)
{ }
This code works.
Correct. Addition has been defined between two objects of type Distance. However the only constructors defined take either no arguments (default constructor) or two arguments -- an int & float. In order for the above statement to compile, there has to be some way that Distance + float can be resolved. By relaxing the definition of the second constructor to accept either one or two arguments:
CPP / C++ / C Code:
Distance(int ft, float in=0.0) : feet(ft), inches(in)  { }
...an object of type Distance can be created for the value 12.25 before invoking overloaded addition between two instances of type Distance. However, note that passing 12.25 to the constructor will result in the implicit conversion from float to int which will truncate the value 12.25 down to 12.
Quote:
Using explicit keyword makes the code stop compiling.
Correct. The purpose of explicit is to flag implicit conversions which may give unexpected results.
Quote:
when i am not using 'explicit', conversion are happening but results are not as desired, because of possible intialization of inches always to 0.0.
Yet, this is the consequence of defaulting the second constructor argument as already discussed. It is not entirely clear what your fundamental question is here, but I see two alternatives which you should consider:
  • Recognize that you can explicitly call whatever constructor you want which will result in an unnamed instance:
    CPP / C++ / C Code:
    dist3 = dist1 + Distance(3, 2.71);
    
  • Likewise, consider further operator overloading:
    CPP / C++ / C Code:
    Distance Distance::operator+(float);
    However, you will need to be careful to ensure that all the overloading can co-exist. Overloading the following:
    CPP / C++ / C Code:
    Distance Distance::operator+(int)
    ...& having the constructor with default arguments:
    CPP / C++ / C Code:
    Distance(int ft, float in=0.0) : feet(ft), inches(in)  { }
    ...can provide multiple paths for a compiler to resolve. Compilers do not like ambiguity, nor should they.
  #4  
Old 09-Jun-2008, 09:50
Archer Archer is offline
Junior Member
 
Join Date: May 2008
Posts: 31
Archer is on a distinguished road

Re: Question related to Operator overloading


yes i forget to remove that line:
Distance dist5=11.35;
Yet keyword explicit practical usability remains mystery for me.
  #5  
Old 09-Jun-2008, 11:38
ocicat ocicat is offline
Regular Member
 
Join Date: May 2008
Posts: 580
ocicat is a jewel in the roughocicat is a jewel in the rough

Re: Question related to Operator overloading


Quote:
Originally Posted by Archer
Yet keyword explicit practical usability remains mystery for me.
Consider the following simplistic implementation of a string class. Only enough code is being provided to prove the point:
CPP / C++ / C Code:
#include <iostream>

using namespace std;

class mystring {
    char *p;
public:
    mystring(int);
    mystring(char*);
};

int
main() {
    mystring s = 'a';

    return 0;
}

mystring::mystring(int i) {
    p = new char[i];
    cout << "execution gets here\t:" << i << endl;
}
In function main(), whoever is using this class appears to be wanting to creating a string with the contents of the single character 'a', however if you compile & execute this code, you will find that mystring::mystring(int) is called instead which interprets the argument in a completely different manner -- 97 (97 is the decimal value of 'a'...) characters is being reserved for the string. This may be obvious in this simple contrived example, but in an application which is hundreds of thousands of lines long, this situation may not be entirely obvious. Better yet, if you were writing such a class & released it into the wild, who is to say that everyone who will be using the code will always use it in the manner intended?

Declaring a constructor an explicit will disallow implicit conversions. Implicit conversions are subtle & they frequently bite people. explicit is an attempt to control this particular problem.
  #6  
Old 09-Jun-2008, 12:27
Archer Archer is offline
Junior Member
 
Join Date: May 2008
Posts: 31
Archer is on a distinguished road

Re: Question related to Operator overloading


Thanks dear!!
  #7  
Old 09-Jun-2008, 18:26
Peter_APIIT Peter_APIIT is offline
Regular Member
 
Join Date: May 2007
Location: Malaysia
Posts: 545
Peter_APIIT can only hope to improve

Re: Question related to Operator overloading


You need to use keywords explicit to force explicit conversion operator.

Explicit constructor only allow to accept one argument.

Danny is my GURU.

I hope this help.
 
 

Recent GIDBlogProblems with the Navy (Chiefs) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Question about locking surfaces to directly access pixels, SDL. george89 C++ Forum 0 18-Jun-2006 22:16
Question re "Similar Pages" on Google jep Search Engine Optimization Forum 0 17-May-2005 10:52
C++ Syntax Highlighter related question JdS GIDForums™ 4 25-Oct-2004 09:00
question of practice magiccreative C++ Forum 1 06-Feb-2004 08:17
'Related articles' php /mysql question JdS MySQL / PHP Forum 4 06-Sep-2002 11:17

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 12:04.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.