Overloaded Constructor in C++


Overloaded Constructor

A constructor that uses different signatures is called overloaded constructor.
since two explicit constructor with the same name , rational () , we say the constructor is overloaded.

class rational
{
private:
int num;
int denum;
public:
rational ( ):num(1 ),denum ( 1)           // this is no argument constructor   also called default argument constructor

{ }

rational (int n , int d  ): num ( n) ,denum(d)              // this is two argument constructor like overloaded constructor
{ }

Here is an example that will clear your idea about that topic.

                                       Example
#include <iostream>
using namespace std;
class rational
{
private:
            int num;
            int dnum;
public:
            rational():num(1),dnum(1)
            {}
            rational(int n ,int d):num(n),dnum(d)
            { }
            void get ()
            {
                        cout<<"enter numerator";
                        cin>>num;
                        cout<<"enter denomenator";
                        cin>>dnum;
            }
            void print ()
            {
                        cout<<num<<"/"<<dnum<<endl;
            }
            void divide(rational r1,rational r2)
            {
                        num=r1.num*r2.dnum;
                        dnum=r1.dnum*r2.num;
            }
};
void main ()
{
            rational r1,r2,r3;
            rational r4(2,3),r5(4,5),r6;
            r1.get();
            r2.get();
            r3.divide(r1,r2);
            r6.divide(r4,r5);


            r3.print();
            r6.print();
}


..........................................................................................................................................................................................


you can solve this program by using add instead of divide  by done just some changes in this program.
·                     use + sign instead of  / .
·                     use add word instead of divide
·                     you can use any arithmatic operator to done this program.