×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to demonstrate example of Parameterized Constructor

Learn about the Parameterized Constructor in C++, how to implement Parameterized Constructor in C++ program?
[Last updated : March 02, 2023]

In this program we will learn to create parameterized constructor program in c++ programming language.

Parameterized Constructor Program in C++

// C++ program to demonstrate example of
// Parameterized Constructor

#include <iostream>
using namespace std;

//Class declaration.
class Demo {
    //Private block  to declare data member( X,Y )
    //of integer type.
private:
    int X;
    int Y;

    //Public block of member function to
    //access data members.
public:
    //Declaration of perameterized constructor to
    //initailize data members.
    Demo(int a, int b);
    //To take input from user.
    void Input();
    //To display output onn screen.
    void Display();

}; //End of class

//Definition of constructor.
Demo::Demo(int a, int b)
{
    X = a;
    Y = b;
}

//Definition of Input() member function.
void Demo::Input()
{
    cout << "Enter Value of X: ";
    cin >> X;
    cout << "Enter Value of Y: ";
    cin >> Y;
}

//Definition of Display() member function.
void Demo::Display()
{
    cout << endl
         << "X: " << X;
    cout << endl
         << "Y: " << Y << endl;
}

int main()
{
    //Ctor autometically call when object is created.
    Demo d(10, 20);

    //Display value of data member.
    cout << endl
         << "Method 1: " << endl;
    cout << "Value after initialization: ";
    d.Display();

    d.Input();
    cout << "Value after User Input : ";
    d.Display();

    //We can also create object like this
    Demo d1 = Demo(10, 20);

    //Display value of data member.
    cout << endl
         << "Method 2: " << endl;
    cout << "Value after initialization: ";
    d1.Display();

    return 0;
}

Output

Method 1: 
Value after initialization: 
X: 10
Y: 20
Enter Value of X: 25
Enter Value of Y: 30
Value after User Input : 
X: 25
Y: 30

Method 2: 
Value after initialization: 
X: 10
Y: 20

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.