C++ Program for Constructor with Parameters(Parameterized Constructor)

By | 31.12.2016

Parameterized Constructor


Write a C++ Program for Constructor with Parameters(Parameterized Constructor). Here’s simple C++ Program for Constructor with Parameters(Parameterized Constructor) in C++ Programming Language.


What are Constructors in C++?


A class constructor is a special member function of a class that is executed whenever we create new objects of that class.

The Compiler calls the Constructor whenever an object is created. Constructors iitialize values to object members after storage is allocated to the object.

class A
{
int x;
public:
A(); //Constructor
};

While defining a contructor you must remeber that the name of constructor will be same as the name of the class, and contructors never have return type.

Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution :: operator.


Below is the source code for C++ Program for Constructor with Parameters(Parameterized Constructor) which is successfully compiled and run on Windows System to produce desired output as shown below :


SOURCE CODE : :


/* C++ Program for Constructor with Parameters(Parameterized Constructor)  */

#include <iostream>
using namespace std;
class MyClass
{
         int h;
         int i;
        public:
            MyClass(int j, int k)
       {
            h = j;
            i = k;
       }
           int getlnt()
       {
           return i;
       }
          int getHeight()
      {
          return h;
      }
};

int main()
{
     MyClass myObject[3] =
     {
         MyClass(7, 6),
         MyClass(1,9),
         MyClass(2,3)

     };

    int i;
    for(i=0; i<3; i++)
    {
        cout<<"\nObject [ "<<i+1<<" ] Heights :: ";
       cout << myObject[i].getHeight();
       cout << ", ";
       cout<< myObject[i].getlnt() << "\n";
    }
  return 0;
}

OUTPUT : :


/* C++ Program for Constructor with Parameters(Parameterized Constructor)  */

Object [ 1 ] Heights :: 7, 6

Object [ 2 ] Heights :: 1, 9

Object [ 3 ] Heights :: 2, 3

Process returned 0

Above is the source code and output for C++ Program for Constructor with Parameters(Parameterized Constructor) which is successfully compiled and run on Windows System to produce desired output.

If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach upto you in the short interval.


Thanks for reading the post….

1.5 2 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments