×

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 Default Constructor or No argument

Learn about the default Constructor or No argument in C++, how to implement default Constructor or No argument in C++ program.
[Last updated : March 02, 2023]

Default Constructor or No argument in C++

In this program we will learn to create default constructor or no argument constructor program in c++ programming language.

Default Constructor or No argument program in C++

// C++ program to demonstrate example of
// Default Constructor or No argument

#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 default or no argument constructor
    //to initialize data members.
    Demo();
    //To take input from user.
    void Input();
    //To display output onn screen.
    void Display();

}; //End of class

//Definition of constructor.
Demo::Demo()
{
    X = 0;
    Y = 0;
}

//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;

    //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();

    //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: 0
Y: 0
Enter Value of X: 23
Enter Value of Y: 24
Value after User Input : 
X: 23
Y: 24

Method 2: 
Value after initialization : 
X: 0
Y: 0

Comments and Discussions!

Load comments ↻





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