Example 1: C++ program to demonstrate the use of class and object
kw.cpp
#include <iostream>
using namespace std;
class kw
{
public:
    void add()
    {
        cout<<"The addition of 10+10="<<10 + 10<<"\n";
    }
};
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:~$
Example 2: C++ program to demonstrate the use of class and object
kw.cpp
#include <iostream>
using namespace std;
class kw
{
public:
    int add(int a, int b)
    {
        return a + b;
    }
};
int main()
{
    kw k;
    cout<<k.add(10, 10)<<endl;
}
Output
kodingwindow@kw:~$ g++ kw.cpp
kodingwindow@kw:~$ ./a.out 20 kodingwindow@kw:~$
Example 3: C++ program to demonstrate the use of class and object
kw.cpp
#include <iostream>
using namespace std;
class kw
{
public:
    void add();
};
void kw::add()
{
    cout<<"The addition of 10+10="<<10 + 10<<"\n";
}
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:~$
Example 4: C++ program to demonstrate the use of class and object
kw.cpp
#include <iostream>
using namespace std;
class kw
{
private:
    int a, b;

public:
    void getdata();
    void add();
};
void kw::getdata()
{
    cout<<"Enter the 1st number ";
    cin>>a;
    cout<<"\nEnter the 2nd number ";
    cin>>b;
}
void kw::add()
{
    if (b < 0)
    {
        cout<<"\nThe addition of "<<a<<b<<" = "<<(a + b)<<"\n";
    }
    else
    {
        cout<<"\nThe addition of "<<a<<"+"<<b<<" = "<<(a + b)<<"\n";
    }
}
int main()
{
    kw k;
    k.getdata();
    k.add();
    return 0;
}
Output
kodingwindow@kw:~$ g++ kw.cpp
kodingwindow@kw:~$ ./a.out Enter the 1st number 10 Enter the 2nd number -50 The addition of 10-50 = -40 kodingwindow@kw:~$
Advertisement