Constructors in C++ Part – 2

Master C++ with Real-time Projects and Kickstart Your Career Start Now!!

Program 1

// Default Constructor , Overloading
#include<iostream>
using namespace std;
class Test
{
    public:
    Test(int x)  // 01 parameter
    {
        cout<<x;
    }
    Test() 
    {
    }
    void display();
  
};
void Test::display()
  {
        cout<<"Hello Friends";
}
int main()
{
    system("cls");
    Test T1(500);   
    Test T2;
    T1.display();
    return 0;
}

Program 2

// Default Constructor , Overloading
#include<iostream>
using namespace std;
class Test
{
    int a,b,c;
    public:
    Test(int x,int y,int z=90)  // 03 parameters
    {
        cout<<"\n03 parameters";
        a=x;
        b=y;
        c=z;
    }
    Test(int x,int y)  // 02 parameters
    {
        cout<<"\n02 parameters";
        a=x;
        b=y;
        c=0;
    }
};
int main()
{
    system("cls");
    Test T1(10,20,30);
    Test T2(50,20);
    
    return 0;
}

Program 3

// Copy Constructor
#include<iostream>
using namespace std;

class Student
{
    int rno;
    string name;
    double per;

    public:
    Student(int srn, string sname,double sper)
    {
        rno=srn;
        name=sname;
        per=sper;
    }
    void display()
    {
         cout<<rno<<"  "<<name<<"   "<<per;
    }
};
int main()
{
    system("cls");
     Student S1(101,"Rajesh",90.55);
     Student S2=S1;  
     
     S1.display();
     S2.display();

    return 0;
}

















// class Test
// {
//       private:
//       int a,b,c;
//      public: 
//       Test(int x,int y,int z)
//       {
//         a=x;
//         b=y;
//         c=z;
//       }
//         void display()
//        {
//          cout<<a<<" "<<b<<"  "<<c<<endl;
//        }
// };

//  int main()
//  {
//      system("cls");
//      Test T1(10,20,30);
//      Test T2=T1;   
//       T1.display();
//       T2.display();
//      return 0;
// }






// class Test
// {
//       private:
//       int n;
//       public:
//       Test(int x)
//       {
//         n=x;
//       }
//       void display()
//       {
//         cout<<n<<endl;
//       }
// };
// int main()
// {
//     system("cls");
//     Test T1(500);  // constructor with integer parameter
//     Test T2=T1;    // copy constructor              explicit
//     Test T2(T1);   // copy constructor with  Test  implicit 
//      T1.display();
//     T2.display();
//     return 0;
// }

 

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *