C++ Online Compiler
Example: Sum of Two Numbers using Basic Class in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of Two Numbers using Basic Class #include <iostream> using namespace std; // Define a class named 'Adder' class Adder { private: int num1; // Private data member to store the first number int num2; // Private data member to store the second number public: // Method to set the two numbers void setNumbers(int a, int b) { num1 = a; num2 = b; } // Method to calculate the sum int calculateSum() { return num1 + num2; } // Method to display the sum void displaySum() { cout << "The sum of " << num1 << " and " << num2 << " is: " << calculateSum() << endl; } }; int main() { // Step 1: Create an object (instance) of the 'Adder' class Adder myAdder; // Step 2: Set the numbers using the 'setNumbers' method myAdder.setNumbers(10, 20); // Step 3: Call the 'displaySum' method to show the result myAdder.displaySum(); return 0; }
Output
Clear
ADVERTISEMENTS