Write a C++ program to add two numbers using the constructor-1.

Write a C++ program to add two numbers using the constructor

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

2 thoughts on “Write a C++ program to add two numbers using the constructor-1.”

  1. My programmer is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the expenses. But he’s tryiong
    none the less. I’ve been using Movable-type on several websites for about a year and am concerned about switching to another
    platform. I have heard good things about blogengine.net.
    Is there a way I can import all my wordpress posts into it?
    Any help would be greatly appreciated!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
NEW TOXIC ROCKET CYCLE DECK in Clash Royale 2023 Best Deck in Clash Royale Best Deck for Arena 8 in Clash Royale Best Hog deck for Pro players Best Clash Royale Deck