operator overloading in Constructors

How do I use operator overloading in a Constructor ?
Pl. explain me with an example .
thanx.
gshankarAsked:
Who is Participating?
 
YuraPhinkConnect With a Mentor Commented:
What do you mean in a Constructor???

simple example of operator overloading:

class A
{
   int aa;
   public:
     
      A(int i=0):aa(i)
      {}
     
      A& operator =(const A &OPR)
      {
          aa=OPR.aa;
         
          return *this;
      }
};

void main()
{
   A cls1,cls2(5);

   cls1=cls2;   //it uses op. =
                //now cls1.aa=cls2.aa=5
/*
   also you can do:
   
   A cls1,cls2(5),cls3(7);

   cls1=cls2=cls3; //this will do:
                   //cls1.aa=cls2.aa=cls3.aa=7
*/

Thats all,
Hope it will help.
}
0
 
YuraPhinkCommented:
OK,
if you mean using operators (which you already defined in the class) in the constructor, then use them as well as in every other function (like in main).
0
 
kaushikgCommented:
Can u give an example how you want to was in ctor??
0
 
KangaRooCommented:
Do you mean conversion?

struct A
{
   int i;  
};

struct B
{
   int j;
   B() : j(0) {}
   B(const A& a) : j(a.i) {}
};


void f(const B& b)
{}

void g()
{
   A a;
   f(a);
}
0
 
gshankarAuthor Commented:
Yes . Iam convinced with YuraPhink's clue.
That cleared my doubt.
Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.