×

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 constructor using this pointer

Learn about the constructors in C++, how to implement constructor using this pointer in C++ program?
[Last updated : March 02, 2023]

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

Constructor using this pointer program in C++

// C++ program to demonstrate example of
// constructor using this pointer.

#include <iostream>
using namespace std;

class Demo {
private: //Private Data member section
    int X, Y;

public: //Public Member function section
    //Default or no argument constructor.
    Demo()
    {
        X = 0;
        Y = 0;

        cout << endl
             << "Constructor Called";
    }
    //Perameterized constructor.
    Demo(int X, int Y)
    {
        this->X = X;
        this->Y = Y;

        cout << endl
             << "Constructor Called";
    }

    //Destructor called when object is destroyed
    ~Demo()
    {
        cout << endl
             << "Destructor Called" << endl;
    }
    //To print output on console
    void putValues()
    {
        cout << endl
             << "Value of X : " << X;
        cout << endl
             << "Value of Y : " << Y << endl;
    }
};

//main function : entry point of program
int main()
{
    Demo d1 = Demo(10, 20);

    cout << endl
         << "D1 Value Are : ";
    d1.putValues();

    Demo d2 = Demo(30, 40);

    cout << endl
         << "D2 Value Are : ";
    d2.putValues();

    //cout << endl ;

    return 0;
}

Output

Constructor Called
D1 Value Are : 
Value of X : 10
Value of Y : 20

Constructor Called
D2 Value Are : 
Value of X : 30
Value of Y : 40

Destructor Called

Destructor Called

Comments and Discussions!

Load comments ↻





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