Open In App

Multiply Function that works for All Numeric Types in C++

Last Updated : 16 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, function overloading allows us to create multiple functions with the same name but different parameter types. Using this concept, we can multiply functions to perform multiplication on numeric values of different data types.

This program should be able to do the following:

  • Multiply two int values.
  • Multiply two double values.
  • Multiply an int and a double (or vice versa).
  • Multiply two numeric strings after converting them to numbers.

Implementation

C++
#include <bits/stdc++.h>
using namespace std;

// Multiply two integers
int multiply(int a, int b) {
    return a * b;
}

// Multiply two doubles
double multiply(double a, double b) {
    return a * b;
}

// Multiply int and double
double multiply(int a, double b) {
    return a * b;
}

// Multiply double and int
double multiply(double a, int b) {
    return a * b;
}

// Multiply two numeric strings
double multiply(const string& a, const string& b) {
    double num1, num2;
    stringstream ss1(a), ss2(b);
    ss1 >> num1;
    ss2 >> num2;
    return num1 * num2;
}

int main() {
    cout << "Int * Int: " << multiply(3, 4) << endl;
    cout << "Double * Double: " << multiply(2.5, 4.0) << endl;
    cout << "Int * Double: " << multiply(3, 4.5) << endl;
    cout << "Double * Int: " << multiply(5.5, 2) << endl;
    cout << "String * String: " << multiply("6.5", "2");
    
    return 0;
}

Output
Int * Int: 12
Double * Double: 10
Int * Double: 13.5
Double * Int: 11
String * String: 13

The compiler chooses the appropriate multiply function based on the argument types. For string inputs, we convert the numeric string values into double using stringstream and then perform multiplication.


Next Article
Article Tags :
Practice Tags :

Similar Reads