C++ Online Compiler
Example: Sum of Two Numbers using Class with Constructor in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of Two Numbers using Class with Constructor #include <iostream> using namespace std; // Define a class named 'AdderWithConstructor' class AdderWithConstructor { private: int num1; int num2; public: // Constructor to initialize num1 and num2 AdderWithConstructor(int a, int b) { num1 = a; num2 = b; cout << "Object created and numbers initialized." << endl; } // 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 of 'AdderWithConstructor', passing numbers directly to the constructor AdderWithConstructor anotherAdder(15, 25); // Step 2: Call the 'displaySum' method to show the result anotherAdder.displaySum(); return 0; }
Output
Clear
ADVERTISEMENTS