Monday, January 7, 2013

Object oriented examples on C++

If you are a beginner for object orientation, please go through the previous post about C++ AS AN OBJECT ORIENTED LANGUAGE and make sure you have a basic idea about its terms.

I thought it's better to explain an object oriented program in C++ with a proper example for you. Go through the following scenario and then follow the steps that I provided for you. 

Target :- 

A bank maintains account details of their customers. You are required to implement the account class declaration in a header file called account.h. The implementation of the class should be saved in the file called account.cpp and the client program should be saved as mainFile.cpp

(1)include the following data members into the account class. 
  • accountNo (integer)
  • customerName(string)
  • accountType(char) --> (Account types are Current-c, Savings-s, Fixed Deposit-f))
  • accountBalance(double)
  • bonusAmount
(2)Implement a constructor which will accept accountNo, customerName,accountType and accountBalance as parameters.

(3) Implement a member function called transactions() which will accept the withdrawal amount and deposit amount as parameters. The function should prompt to enter what kind of transaction you have to do and user will select the appropriate transaction by inputting the first letter of the transaction type. That is 'w' for withdraw and 'd' for deposit. The function should calculate the final accountBalance after doing the transaction.

(4) Implement a member function called bonus() to calculate the bonusAmount according to the available account balance. Use the following criteria to update the bonusAmount

Account type                       Criteria

Current Account                   If the account balance is greater than or equal to Rs. 1000000 give 1% bonus                 

                                            from the account balance else no bonus

Fixed Deposit                      No bonus

Savings Account                  If the account balance is greater than or equal to Rs. 1000000 give 10% bonus
                                           from the account balance
                                           If the account balance is less than Rs.1000000 and greater than or equal to
                                           Rs.10000 give 5% bonus from the account balance.
                                           If the account balance is less than 10000 give 2% bonus from the account        

(5) implement a member function called print() to print the details of an account. The output format should be look like as follows (use iomanip library for the formatting)

Account Number :                        98765432156
Customer Name:                             Kevin Shelly
Account Type:                                        Savings
Account Balance :                                15426.50
Bonus Amount:                                      3639.17

(6) Implement a client program called mainFile.cpp and create two customer objects with the following details.
                                                             Object1                        Object2

Account Number :                        98765432156                1256354896
Customer Name:                             Kevin Shelly            Kamalini Perera
Account Type:                                        Savings                         Current
Account Balance :                                15426.50                     64000.00

(7) Then do the following transactions for the above created objects

Account Number      transaction  type   amount
98765432156             withdrawal        12500.00
1256354896               Deposit             66000.00
98765432156             Deposit             40000.00
1256354896               withdrawal        48000.00

(8) Print the two object details using print() function.

OK, let's start the coding keeping all the object oriented concepts in mind.

We are not going to have one program in one file, compile and run it like in the previous post. Of course, we can do things like that but OOP gives us more organized ways for programming. so, we'll follow them.
basically we are going to have three files here.

  1. header file to declare the private attributes and public methods in one class---->account.h
  2. implementation file which implements all the method that are declared in the header file-->account.cpp
  3. file which contains the main program to start the program execution as we required.-->mainFile.cpp
First, you my ask me why we are having three files if we can do everything in one file. One of the main reason for that is code re usability. other reasons are modifiablity, understandability and organization.

I'll start explain the very first file which is going to be the header file.
  • first identify the attributes that you must include under an account class. They are straight away given in the target example. make them private (you are not going to allow outsiders to meddle with them because they are going to contain data)
  • next think what are the operations that you are going to perform in an account class as  performing transactions, calculating bonus amounts, printing information. Also think how you are going to initialize data to an account (create an account with given information)
  • do not give the same name of the attributes to the function parameters. this avoids coonfusions to the compiler
  • create a class contain the above attributes and methods and save it as account.h
here's the source code.

//account.h contains the accoutn class
class account
private:                                                 //private attributes goes here
long int accountNo;
char customerName[20];
char accountType;
double accountBalance;
double bonusAmmount;

public:                                                //public methods goes here            
account(long int paccountNo,char pcustomerName[],char paccountType,double paccountBalance);
void transactions(double withdrawelAmount,double depositAmount);
void bonus();
void print();


  • now, open a new text editor and start making the implementation file called account.cpp
  • do not forget to include the account.h file on top. else, the program wont know the attributes and methods  that we are using here are declared
  • before every method's name in the function header, mention the class's name with two colons
    • ex:- void account : : print(){}
  •  do the function implentation using the given instructions. if there are no any return types, make it void 
  • make the constructor the very first function because there where you are going to initialize the attributes with data. 

constructor is a special method of a class which has the same name of the class and with no return types. it can have zero ore more parameters. even if you didn't mention a constructor in your program, the compiler will consider the default constructor which has no parameters. because a class must have at least one parameter. whenever you create an object of a class, you implicitly calling the constructor of the class.

#include "account.h"
using namespace std;

//parameterized  constructor
account::account(long int paccountNo,char pcustomerName[],char paccountType,double paccountBalance)

//this method handles the transactions done to an account
void account::transactions(double withdrawelAmount,double depositAmount)

//this method calculates the bonus amount using the conditions to calculate bonus
void account::bonus()

else if(accountType=='s')
else if(accountBalance<1000000.00 && accountBalance>=10000.00)

else if(accountBalance<10000.00 && accountBalance>=0.00)

//this method will print the results after formatting
void account::print()

char accType[20];
cout<<setw(25)<<left<<"Account Number"<<setw(25)<<right<<accountNo<<endl;
cout<<setw(25)<<left<<"Customer Name"<<setw(25)<<right<<customerName<<endl;

else if(accountType=='c')
else if(accountType=='f')
strcpy(accType,"Fixed Deposit");

cout<<setw(25)<<left<<"Account Type"<<setw(25)<<right<<accType<<endl;
cout<<setw(25)<<left<<"Account Balance"<<setw(25)<<right<<accountBalance<<endl;
cout<<setw(25)<<left<<"Bonus Amount"<<setw(25)<<right<<bonusAmmount<<endl<<endl;


setw() is a function from the iomanip library which is used to allocate spaces for some output. for an example, i have used setw(25) to print the Account Number which means, it allocates 25 spaces to print Account Number. the remaining spaces will be left blank (nothing will be printed there)

also note that by mentioning left or right before some variable to print in cout function, you can format your output as you wish.

now, the biggest task is over. just because we have a header file and an implementation file with us, noting will happen. To do a task  we have to instruct the compiler through a program file which contains the main method. did you notice that none of our above two files don't have a main method. Now the below file is for that.
  • open a new text editor and type the below code and save as mainFile.cpp
  • do not forget to include the account.h header file on top
  • you can't just call functions because in OOP we have to maintain communication via objects.  So, create an object.
  • as I already said, when you create an object, the constructor will be automatically involved. so, pass values to the constructor in the exact order that we have declared.
  • if you want to access a function use the object name along with the DOT (.) operator. if the function returns a value, then have a variable to capture it.
  • you can create any number of objects and do tasks as you wish.

#include "account.h"
using namespace std;

int main()
account customer1(9876543215,"Kevin Shelly",'s',15426.50);

account customer2(1256354896,"Kamalini Perera",'c',64000.00);

return 0;

How to compile the program when it have multiple files?

now you have a header file and two cpp files. this is how the command for compilation should be.

g++ -oaccount account.cpp mainFile.cpp

How to run the program?


now, you should observe the following output.

you can download more examples on OOP in C++ from HERE