Constructors in C++ Part – 1

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

Program 1

// Constructor in CPP
#include<iostream>
using namespace std;
class Test
{
     private:
     int a,b,c;
     public:
     Test(int x,int y)   // parameterized   constructor 
     {
          a=x;
          b=y;
         cout<<"\nI am constructor\n";
         
     }
    void add();
};
void Test::add()
{
    c=a+b;
    cout<<c<<endl;
}

int main()
{
    system("cls");
     int a,b;
     cout<<"Enter two number";
     cin>>a>>b;
    Test T1(a,b);  // argument 
    Test T2(500,500); // argument 
     T1.add();
     T2.add();

    return 0;
}

Program 2

// Constructor in CPP
#include<iostream>
using namespace std;
class Test
{
     private:
       int a,b,c;   
     public:
     Test(int x=50,int y,int z=100)   // 3 parameter
     {
          a=x;
          b=y;
          c=z;
     }
     void display()
     {
        cout<<"a="<<a<<endl;
        cout<<"b="<<b<<endl;
        cout<<"c="<<c<<endl;
     }
}; 
int main()
{
    system("cls");
     Test T1(200);  // 2 argument
      T1.display();
    return 0;
}

Your opinion matters
Please write your valuable feedback about DataFlair 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 *