C++ Programs on OOP
Posted by Superadmin on August 08 2022 07:54:39
C++ Programs on OOP
- C++ Program to Illustrate Abstract Class
- C++ Program to Differentiate Between Concrete Class and Abstract Class
- C++ Program to Illustrate Nested Classes
- C++ Program to Implement a Class Date
- C++ Program to Add Two Complex Numbers using Class
- C++ Program to Illustrate Const Keyword with Member Functions
- C++ Program to Implement a Class with Mutable Members
- C++ Program to Demonstrate the use of Static Data Members in a Class
- C++ Program to Demonstrate Order of Constructor and Destructor Calls
- C++ Program to Illustrate Copy Constructor in a Class
- C++ Program to Illustrate the use of Enumerations
- C++ Program to Demonstrate the use of Keyword Friend
- C++ Program to Implement atol Function
- C++ Program to Demonstrate User Defined Exceptions
Abstract Class Program in C++
This C++ program illustrates abstract classes. Abstract classes are used to represent general concepts, which can be used as base classes for concrete classes. An abstract class is one which has atleast one purely virtual function. We can not create instance of such class. The program creates a derived class whose instance is created and is manipulated.
Here is the source code of the C++ program which illustrates abstract classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C++ Program to Illustrate Abstract Class
-
*/
-
#include <iostream>
-
using namespace std;
-
-
class Abstract {
-
int i, j;
-
public:
-
virtual void setData(int i = 0, int j = 0) = 0;
-
virtual void printData() = 0;
-
};
-
-
class Derived : public Abstract {
-
int i, j;
-
public:
-
Derived(int ii = 0, int jj = 0) : i(ii), j(jj)
-
{
-
cout << "Creating object " << endl;
-
}
-
void setData(int ii = 0, int jj = 0)
-
{
-
i = ii;
-
j = jj;
-
}
-
void printData()
-
{
-
cout << "Derived::i = " << i << endl
-
<< "Derived::j = " << j << endl;
-
}
-
};
-
-
int main()
-
{
-
// Cannot create an instance of Abstract Class
-
// Abstract a;
-
Derived d;
-
-
cout << "Current data " << endl;
-
d.printData();
-
d.setData(10, 20);
-
cout << "New data " << endl;
-
d.printData();
-
}
$ a.out
Creating object
Current data
Derived::i = 0
Derived::j = 0
New data
Derived::i = 10
Derived::j = 20
Difference between Concrete Class and Abstract Class in C++
This C++ program differentiates between the concrete and abstract class. An abstract class is meant to be used as a base class where some or all functions are declared purely virtual and hence can not be instantiated. A concrete class is an ordinary class which has no purely virtual functions and hence can be instantiated.
Here is the source code of the C++ program which differentiates between the concrete and abstract class. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C++ Program to differentiate between concrete class and abstract class
-
*/
-
#include <iostream>
-
#include <string>
-
using namespace std;
-
-
class Abstract {
-
private:
-
string info;
-
public:
-
virtual void printContent() = 0;
-
};
-
-
class Concrete {
-
private:
-
string info;
-
public:
-
Concrete(string s) : info(s) { }
-
void printContent() {
-
cout << "Concrete Object Information\n" << info << endl;
-
}
-
};
-
-
int main()
-
{
-
/*
-
* Abstract a;
-
* Error : Abstract Instance Creation Failed
-
*/
-
string s;
-
-
s = "Object Creation Date : 23:26 PM 15 Dec 2013";
-
Concrete c(s);
-
c. printContent();
-
}
$ a.out
Concrete Object Information
Object Creation Date : 23:26 PM 15 Dec 2013
Nested Class Program in C++
This C++ program illustrates the use of nested classes. The program uses Node class as a member for Stack class where Node class is nested inside Stack class. The Node class is local to Stack class which can be used outside Stack’s context by using scope operator ‘::’.
Here is the source code of the C++ program illustrates the use of nested classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C++ Program to Illustrate Nested Classes
-
*/
-
#include <iostream>
-
-
class Stack {
-
class Node {
-
public:
-
int data;
-
Node* next;
-
Node(int data, Node* next);
-
~Node();
-
}* head;
-
public:
-
Stack();
-
Stack(const Stack& s);
-
void operator=(const Stack& s);
-
~Stack();
-
void push(int data);
-
int peek() const;
-
int pop();
-
};
-
-
Stack::Node::Node(int data, Node* next)
-
{
-
this->data = data;
-
this->next = next;
-
}
-
-
Stack::Node::~Node() { }
-
-
Stack::Stack() { head = NULL; }
-
-
Stack::Stack(const Stack& s)
-
{
-
head = s.head;
-
}
-
-
void Stack::operator=(const Stack& s)
-
{
-
head = s.head;
-
}
-
-
void Stack::push(int data)
-
{
-
head = new Node(data, head);
-
}
-
-
int Stack::peek() const {
-
if(head == 0)
-
{
-
std::cerr << "Stack empty!" << std::endl;
-
return -1;
-
}
-
else
-
return head->data;
-
}
-
-
int Stack::pop()
-
{
-
if(head == NULL) return -1;
-
int result = head->data;
-
Node* oldNode = head;
-
head = head->next;
-
delete oldNode;
-
return result;
-
}
-
-
Stack::~Stack()
-
{
-
if(head != NULL)
-
{
-
while(head->next != NULL)
-
{
-
Node* temp = head;
-
head = head->next;
-
delete temp;
-
}
-
}
-
}
-
-
int main()
-
{
-
Stack Integers;
-
int value, num;
-
-
std::cout << "Enter the number of elements ";
-
std::cin >> num;
-
while(num > 0)
-
{
-
std::cin >> value;
-
Integers.push(value);
-
num--;
-
}
-
while (( value = Integers.pop() ) != -1)
-
std::cout << "Top element of stack " << value << std::endl;
-
}
$ a.out
Enter the number of elements 5
1 2 3 4 5
Top element of stack 5
Top element of stack 4
Top element of stack 3
Top element of stack 2
Top element of stack 1
Date Class Implementation in C++
This C++ program implements a class – Date. The class uses time header contains a function time() which returns current calender time as an object of type time_t. We can extract various information from this struct by using -> with the pointer to the time structure.
Here is the source code of the C++ program implements a class – Date. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C++ Program to implement Class Date
-
*/
-
#include <iostream>
-
#include <ctime>
-
-
std::string months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
-
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
-
std::string days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri",
-
"Sat"};
-
-
class Date{
-
// Private Members
-
private:
-
std::string month;
-
std::string day;
-
int date;
-
int year;
-
// Public Members
-
public:
-
// Default Constructor
-
Date() {
-
const int BASE_YEAR = 1900;
-
time_t timer;
-
tm * time;
-
std::time(&timer);
-
time = localtime(&timer);
-
date = time->tm_mday;
-
month = months[time->tm_mon];
-
day = days[time->tm_wday];
-
year = time->tm_year + BASE_YEAR;
-
}
-
void printDate(void) {
-
std::cout << "Current date "
-
<< this->month << " " << this->day << " "
-
<< this->date << " " << this->year;
-
}
-
// Destructor
-
~Date() {}
-
};
-
-
int main()
-
{
-
Date d;
-
-
d.printDate();
-
}
$ a.out
Current date Oct Mon 7 2013
C++ Program to Add Two Complex Numbers using Class
This is a C++ Program to add two Complex Numbers.
Problem Description
We have to input the real and imaginary parts of two complex numbers separately and add them using classes and objects in C++.
Expected Input and Output
1. When the real and imaginary part both are positive.
First Complex Number = 5 + 6i
Second Complex Number = 1 + 3i
Output= 6 + 9i
2. When any one of the imaginary or real part is negative.
First Complex Number = -4 + 6i
Second Complex Number = 5 + (-3i)
Output= 1 + 3i
3. When both real and imaginary parts are negative.
First Complex Number = -5 + -(6i)
Second Complex Number = -3 + -(5i)
Output= -8 + -11i
Problem Solution
In this problem, we are going to create a function that adds two complex numbers. First the user has to provide real and imaginary parts as input for both the complex numbers. After that the real part of first complex number will be added with the real part of second one, similarly the imaginary part of first complex number will be added with the imaginary part of second complex number.
Program/Source Code
Here is source code of the C++ Program to add two Complex Numbers using Classes and Objects. The program is successfully compiled and tested using Codeblocks gnu/gcc compiler on Windows 10. The program output is also shown below.
-
/* C++ Program to add two Complex Numbers */
-
#include<iostream>
-
using namespace std;
-
class Complex{
-
public:
-
int real;
-
int imag;
-
/* Function to set the values of
-
* real and imaginary part of each complex number
-
*/
-
void setvalue()
-
{
-
cin>>real;
-
cin>>imag;
-
}
-
/* Function to display the sum of two complex numbers */
-
void display()
-
{
-
cout<<real<<"+"<<imag<<"i"<<endl;
-
}
-
/* Function to add two complex numbers */
-
-
void sum(Complex c1, Complex c2)
-
{
-
real=c1.real+c2.real;
-
imag=c1.imag+c2.imag;
-
}
-
};
-
int main()
-
{
-
Complex c1,c2,c3;
-
cout<<"Enter real and imaginary part of first complex number"<<endl;
-
c1.setvalue();
-
cout<<"Enter real and imaginary part of second complex number"<<endl;
-
c2.setvalue();
-
cout<<"Sum of two complex numbers is"<<endl;
-
c3.sum(c1,c2);
-
c3.display();
-
return 0;
-
}
Program Explanation
Here in this program we have created a few functions.
1. setvalue()
This function allows us to take input for real and imaginary parts of both the complex numbers. To take in real and imaginary part as an input for first complex number we have called this function using an object c1. So, this function sets the real and imag values for first complex number. Similarly to set the values of real and imaginary part of second complex number, we can call it using a new object c2.
2. sum()
This function takes in two complex numbers as a parameter. Using this function we have added the real parts of both the complex numbers together and stored them into variable real which is the real part of the resultant complex number. Similarly we have added the imaginary parts of both the complex numbers and stored the result into variable imag which is the imaginary part of the resultant complex number.
3. display()
We have called this function using an object for the resultant complex number, to display the real and imaginary parts of the resultant complex number obtained after addition.
Runtime Test Cases
1. Enter real and imaginary part of first complex number
5
6
Enter real and imaginary part of second complex number
1
3
Sum of two complex numbers is
6+9i
2. Enter real and imaginary part of first complex number
-4
6
Enter real and imaginary part of second complex number
5
-3
Sum of two complex numbers is
1+3i
3. Enter real and imaginary part of first complex number
-5
-6
Enter real and imaginary part of second complex number
-3
-5
Sum of two complex numbers is
-8+-11i
C++ Program to Illustrate Const Keyword with Member Functions
This C++ program illustrates the const keyword with member functions. The functions with a const keyword specified before the function definition prevents the calling of non-const data members for a given instance of the class. It also prevents t
Here is the source code of the C++ program which illustrates the const keyword with member functions. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C++ Program to illustrate physical constness
-
*/
-
#include <iostream>
-
#include <string>
-
#include <sstream>
-
using namespace std;
-
-
class A {
-
private:
-
int i, j;
-
public:
-
A(int ii = 0, int jj = 0) : i(ii), j(jj) {}
-
void changeData(int ii, int jj ) {
-
i = ii;
-
j = jj;
-
}
-
string getResponse() const {
-
string s;
-
stringstream ss;
-
ss << "i = " << i << ", j = " << j << "\n";
-
s = ss.str();
-
return s;
-
}
-
void makeSomeChanges() const;
-
-
};
-
-
/*
-
* Can't change A::i or A::j
-
void A::makeSomeChanges() const {
-
i = i + 10;
-
j = j + 10;
-
}
-
*/
-
-
int main()
-
{
-
A a(10, 20);
-
-
cout << "A a(10, 20) : " << a.getResponse();
-
a.changeData(30, 40);
-
cout << "A::changeData(30, 40) : " << a.getResponse();
-
// a.makeSomeChanges();
-
cout << "A::makeSomeChanges() : " << a.getResponse();
-
}
$ a.out
A a(10, 20) : i = 10, j = 20
A::changeData(30, 40) : i = 30, j = 40
A::makeSomeChanges() : i = 30, j = 40
C++ Program to Implement a Class with Mutable Members
This C++ program illustrates the concept of mutable keyword in classes. The keyword mutable enables a const member function to change a variable. This explains the concept of logical const-ness of the object where the object changes in a way that it is not apparent through a public interface.
Here is the source code of the C++ program illustrates the concept of mutable keyword in classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C++ Program to Implement a Class with Mutable Members
-
*/
-
#include <iostream>
-
-
class A {
-
private:
-
int i;
-
mutable int j;
-
public:
-
A(int ii = 0, int jj = 1) : i(ii), j(jj) { }
-
void change() const;
-
void print();
-
};
-
-
void A::change() const
-
{
-
// Mutable variable
-
j++;
-
}
-
-
void A::print()
-
{
-
std::cout << "A::i = " << i << std::endl
-
<< "A::j = " << j << std::endl;
-
}
-
-
int main()
-
{
-
A a;
-
-
std::cout << "Before A::change()" << std::endl;
-
a.print();
-
a.change();
-
std::cout << "After A::change()" << std::endl;
-
a.print();
-
}
$ a.out
Before A::change()
A::i = 0
A::j = 1
After A::change()
A::i = 0
A::j = 2
C++ Program to Demonstrate the use of Static Data Members in a Class
This C++ program demonstrates the use of static members in a class. A static data member is shared by all objects of a class. We can put a static data member inside a class but we would have to initialize it outside the class using scope resolution operator (::).
Here is the source code of the C++ program demonstrates the use of static members in a class. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C++ Program to Demonstrate a Class with Static Members
-
*/
-
#include <iostream>
-
-
class Car {
-
private:
-
static std::string colour;
-
std::string brand;
-
std::string state;
-
int model;
-
public:
-
Car(int model, std::string brand, std::string state = "off")
-
{
-
this->model = model;
-
this->brand = brand;
-
this->state = state;
-
}
-
void engineOn()
-
{
-
state = "on";
-
}
-
void knowState()
-
{
-
std::cout << "Is " << brand << " ready?" << std::endl;
-
}
-
void isReady()
-
{
-
if(state == "on")
-
std::cout << colour << " " << brand
-
<< " is ready to go!" << std::endl;
-
else
-
std::cout << colour << " " << brand
-
<< " is not ready!" << std::endl;
-
}
-
};
-
-
// Definition of a protected static member
-
// Legal expression
-
std::string Car::colour = "Red";
-
-
int main()
-
{
-
Car chevy(1965, "Chevy Mint", "on");
-
chevy.knowState();
-
chevy.isReady();
-
Car ferrari(1965, "Ferrari" );
-
ferrari.knowState();
-
ferrari.isReady();
-
}
$ a.out
Is Chevy Mint ready?
Red Chevy Mint is ready to go!
Is Ferrari ready?
Red Ferrari is not ready!
Order of Constructor and Destructor Calls in C++
This C++ program demonstrates the order of constructor and destructor calls for globally and locally initialized objects. The constructors of global objects are initialized earlier than local objects and the destructors for local objects are called earlier than global objects. Thus we can say that scope of a global object is larger than a local objects.
Here is the source code of the C++ program demonstrates the order of constructor and destructor calls for globally and locally initialized objects. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C++ Program to demonstrate order of constructor and destructor calls
-
*/
-
#include <iostream>
-
-
class A {
-
int i;
-
public:
-
A(int ii = 0) : i(ii)
-
{
-
std::cout << "A::A" << i << "() constructor "
-
<< std::endl;
-
}
-
~A()
-
{
-
std::cout << "A::~A" << i << "() destructor "
-
<< std::endl;
-
}
-
};
-
-
A a1(1);
-
-
int main()
-
{
-
A a2(2);
-
}
$ a.out
A::A1() constructor
A::A2() constructor
A::~A2() destructor
A::~A1() destructor
Copy Constructor Program in C++
This C++ program illustrates copy-constructor in a class. A copy constructor is a special constructor for a class that is used to make a copy of an existing instance of the class. A copy-constructor looks like a constructor with an object of same class as an argument.
Here is the source code of the C++ program which illustrates copy-constructor in a class. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
1. /*
2. * C++ Program to illustrate copy-constructor in a class
3. */
4. #include <iostream>
5. using namespace std;
6.
7. class Base {
- 8. int i;
- 9. public:
- Base(int ii = 0): i(ii) { }
- Base(const Base& b)
- {
- this->i = b.i;
- }
- void setData(int ii) { i = ii; }
- int getData() { return i; }
17.};
18.
19.int main()
20.{
- Base b;
22.
- cout << "b::getData = " << b.getData() << endl;
- cout << "b::setData = 10" << endl;
- b.setData(10);
- cout << "b::getData = " << b.getData() << endl;
- cout << "Calling copy-constructor on c" << endl;
- Base c(b);
- cout << "c::getData = " << c.getData() << endl;
30.}
$ a.out
b::getData = 0
b::setData = 10
b::getData = 10
Calling copy-constructor on c
c::getData = 10
Enumerations Program in C++
This C++ Program which illustrates the use of enumerations. The program creates an enumeration of months, creates an enumeration variable, assigns it a month value and prints a comment on the current month.
Here is source code of the C++ program which illustrates the use of enumerations. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
-
* C++ Program to Illustrate the use of Enumerations
-
*/
-
-
#include<iostream>
-
using namespace std;
-
-
enum Month {January = 1 ,February = 2, March = 3, April = 4, May = 5,
-
June = 6, July = 7, August = 8, September = 9, October = 10,
-
November = 11, December = 12};
-
-
int main()
-
{
-
Month month;
-
month = August;
-
-
cout << "The month is August." << endl;
-
/* Printing comments on current Month */
-
if (month >= March && month <= May)
-
cout << "Yay, It is Spring!" << endl;
-
else if (month >= June && month <= August)
-
cout << "It is Summer, Who needs an Ice Cream?" << endl;
-
else if (month >= September && month <= November)
-
cout << "I am enjoying Autumn, Aren't You?" << endl;
-
else
-
cout << "Ooh, It is very cold outside! It's Winter!" << endl;
-
}
$ g++ main.cpp
$ ./a.out
The month is August.
It is Summer, Who needs an Ice Cream?
Friend Function Program in C++
This C++ program demonstrates the use of keyword friend in classes. The program creates two classes ‘X’ and ‘Y’ and declares one class as ‘friend’ in another. By declaring friend, we mean that the friend class ‘Y’ will gain access to all the data members of the class ‘X’. The member functions of the friend class ‘Y’ can now change the values of data member of objects of class ‘X’ when passed as parameters.
Here is the source code of the C++ program demonstrates the use of keyword friend in classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Demonstrate the use of Keyword Friend
*/
#include <iostream>
class X {
private:
int j;
protected:
int k;
public:
X(int jj = 1, int kk = 2) : j(jj), k(kk) {}
friend class Y;
friend void fun();
};
class Y {
int l;
public:
Y(int ll = 0) : l(ll) {}
void change(const X& x);
void printValue()
{
std::cout << "Y::l = " << l << std::endl;
}
};
void Y::change(const X& x)
{
l = x.j;
std::cout << "Y::change() : Y::l is now X::j " << std::endl;
}
void fun()
{
X x;
std::cout << "fun::X::j = " << x.j << std::endl;
}
int main()
{
X x;
Y y;
y.printValue();
fun();
y.change(x);
y.printValue();
}
$ a.out
Y::l = 0
fun::X::j = 1
Y::change() : Y::l is now X::j
Y::l = 1
C++ Program to Implement atol Function
This C++ Program which implements atol function which converts a C++ string to an integer value. The function atol( ) skips any trailing blanks and alphabets and if the string iterator has reached the end of the string, a negative value is returned to indicate that no digit is present in the string else the iterator goes through the remaining string until a non-digit character is encountered.
Here is source code of the C++ program which implements atol function which converts a C++ string to an integer value. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
-
* C++ Program to Implement atol Function
-
*/
-
#include <iostream>
-
#include <cctype>
-
#include <string>
-
-
/* Function converts string to integer */
-
int atol(std::string s)
-
{
-
int num = 0;
-
std::string::const_iterator i;
-
for (i = s.begin(); i != s.end(); i++)
-
{
-
if (*i == ' ' || *i == '\t' || isalpha(*i))
-
continue;
-
else
-
break;
-
}
-
if (i == s.end())
-
return -1;
-
for (std::string::const_iterator j = i; j != s.end(); j++)
-
{
-
if (isdigit(*j))
-
num = num * 10 + (*j - '0');
-
else
-
break;
-
}
-
return num;
-
}
-
-
int main()
-
{
-
std::string s;
-
int num;
-
std::cout << "Enter a numerical string : ";
-
std::cin >> s;
-
num = atol(s);
-
if (atol(s) >= 0)
-
std::cout << "The Numerical Value is : " << num << std::endl;
-
else
-
std::cout << "No numerical digit found " << std::endl;
-
}
$ g++ main.cpp
$ ./a.out
Enter a numerical string : 956
The Numerical Value is : 956
$ ./a.out
Enter a numerical string : nonumber
No numerical digit found
User Defined Exceptions in C++
This C++ program demonstrates user-defined exceptions. The program derives an exception class from the standard exception class named Divide_By_Zero_Exception. The try block throws the Divide_By_Zero_Exception object and catch block handles it by executing the what() member function.
Here is the source code of the C++ program which demonstrates user-defined exceptions. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C++ Program to demonstrate user-defined exceptions
-
*/
-
#include <iostream>
-
#include <exception>
-
using namespace std;
-
-
class Divide_By_Zero_Exception : public exception{
-
public:
-
const char * what() const throw()
-
{
-
return "Divide By Zero Exception\n";
-
}
-
};
-
-
int main()
-
{
-
try
-
{
-
int a, b;
-
cout << "Enter two numbers : ";
-
cin >> a >> b;
-
// compute a / b
-
if (b == 0)
-
{
-
Divide_By_Zero_Exception d;
-
throw d;
-
}
-
else
-
{
-
cout << "a / b = " << a/b << endl;
-
}
-
}
-
catch(exception& e)
-
{
-
cout << e.what();
-
}
-
}
$ a.out
Enter two numbers : 10 2
a / b = 5
$ a.out
Enter two numbers : 1 0
Divide By Zero Exception