C++ program to print the addition of numbers using default constructor
kw.cpp
#include <iostream>
using namespace std;
class kw
{
    int a, b;

public:
    void add()
    {
        cout<<"The addition of "<<a<<"+"<<b<<"="<<(a + b)<<"\n";
    }
    kw()
    {
        a = 10;
        b = 10;
    }
};
int main()
{
    kw k;
    k.add();
    return 0;
}
Output
kodingwindow@kw:~$ g++ kw.cpp
kodingwindow@kw:~$ ./a.out The addition of 10+10=20 kodingwindow@kw:~$
C++ program to print the addition of numbers using parameterized constructor
kw.cpp
#include <iostream>
using namespace std;
class kw
{
    float a, b;

public:
    void add()
    {
        cout<<"The addition of "<<a<<"+"<<b<<"="<<(a + b)<<"\n";
    }
    kw()
    {
        a = 10, b = 10;
    }
    kw(int x, float y)
    {
        a = x;
        b = y;
    }
};
int main()
{
    kw k, d(10, 10.02351);
    k.add();
    d.add();
    return 0;
}
Output
kodingwindow@kw:~$ g++ kw.cpp
kodingwindow@kw:~$ ./a.out The addition of 10+10=20 The addition of 10+10.0235=20.0235 kodingwindow@kw:~$
What Next?
C++ Functions
Advertisement