Example 1

#include<iostream>
using namespace std;
 class test
{
public:
    int x;
    int y;
    int c;
    test()
    {
        cin>>x>>y;
        c=x+y;
        cout<<c;

    }
};
int main()
{
    test a;

}

Input: 5 6

Output: 11

Explanation

The C++ program above creates a class named “test” that has three integer variables: x, y, and c. It also has a constructor method that takes no arguments and initializes x and y by reading two integers from the standard input (using the “cin” function). Then, it calculates the sum of x and y and stores it in c. Finally, it outputs the value of c to the standard output (using the “cout” function).

In the main function, an instance of the “test” class is created, which automatically calls the constructor method. This results in the sum of the two input numbers being printed to the console.

Overall, this program demonstrates how to use a constructor to initialize the values of a class’s member variables and perform some computations based on those values.

Object-Oriented Programming | C++ | Data Structures and Algorithms

Leave a Comment