Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

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        
                                           balance

(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"
#include<iostream>
#include<cstring>
#include<iomanip>
using namespace std;

//-----------------------------------------------------------------------------------------------------------
//parameterized  constructor
account::account(long int paccountNo,char pcustomerName[],char paccountType,double paccountBalance)
{
accountNo=paccountNo;
strcpy(customerName,pcustomerName);
accountType=paccountType;
accountBalance=paccountBalance;
}

//-----------------------------------------------------------------------------------------------------------
//this method handles the transactions done to an account
void account::transactions(double withdrawelAmount,double depositAmount)
{
accountBalance=accountBalance-withdrawelAmount;
accountBalance=accountBalance+depositAmount;
}

//-----------------------------------------------------------------------------------------------------------
//this method calculates the bonus amount using the conditions to calculate bonus
void account::bonus()
{
bonusAmmount=0.00;
if(accountType=='c')
{
if(accountBalance>=1000000.00)
{
bonusAmmount=accountBalance*0.01;
}
}

else if(accountType=='s')
{
if(accountBalance>=1000000.00)
{
bonusAmmount=accountBalance*0.10;
}
else if(accountBalance<1000000.00 && accountBalance>=10000.00)
{
bonusAmmount=accountBalance*0.05;
}

else if(accountBalance<10000.00 && accountBalance>=0.00)
{
bonusAmmount=accountBalance*0.02;
}
}
}

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

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

if(accountType=='s')
strcpy(accType,"Savings");
else if(accountType=='c')
strcpy(accType,"Current");
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;
cout<<"-----------------------------------------------------------------"<<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"
#include<iostream>
using namespace std;

int main()
{
account customer1(9876543215,"Kevin Shelly",'s',15426.50);
customer1.transactions(12500.00,0.0);
customer1.transactions(0.0,40000.00);
customer1.bonus();
customer1.print();

account customer2(1256354896,"Kamalini Perera",'c',64000.00);
customer2.transactions(0.0,66000.00);
customer2.transactions(48000.00,0.0);
customer2.bonus();
customer2.print();

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?

./account

now, you should observe the following output.



















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

Friday, January 4, 2013

C++ as an object oriented language

I'm sure that you have at least a little idea about what the object oriented concept is. Before going in depth about C++ as an object oriented language I hope we have to clarify some more things about it.

The major purpose of C++ programming was to add object orientation to the C programming language, which is in itself one of the most powerful languages.

What is an object oriented language?

The core of the pure object oriented programming is to create an object, in code that has certain properties and methods. While designing C++ modules, we try to see the entire world in terms of objects. For an instance a Student is an object which has certain properties such as name, studentID, address, GPA etc . It also has certain methods such as doExam, register and so on.

Is C++ a pure object oriented language?

I think if you have already followed the previous posts of C++, you should know the answer for this partially.     If this language is a  pure object oriented language, you should be able to write the programs completely using objects. C++ supports object orientation but Object orientation is not intrinsic to the language. Did you notice that C++ programs always have a main method and it is not a member of an object.

The big arguments people have against declaring C++ as "pure" is that it still requires at least one non object orientation bit, main() and that not everything is an object. for an instance, int,long,float are just primitive variable types that do not belong to any class. 

As a conclusion, I can say that C++ is not a pure object oriented language but you can still follow object oriented concepts in C++. Let's call C++ as a hybrid object oriented language as it is based on C which is a pure procedural language.

For your knowledge, keep in mind that C# and java are pure object languages.

So, we are close to enter to the world of Object Orientation. I think the best is to be familiar with the terms used in Object Orientation.

Object

An object is the basic unit of object oriented programming. That is, both data and function that operate on data are bundled as a unit called as object.

Class

We can call a class as a blue print of an object. A class doesn't define any data but it does define what the class name means, that is what an object of the class will consist of and what operations can be performed on such an object.

Abstraction

This says how OO provides only essential information to the outside world and hide their background details. that is to represent the needed information in program without presenting the details .

Just think how a database works. You just know what is stored in a database not how because the background details of a database are always hidden and it displays the abstract data all the time. Similar way C++ classes provides different methods to the outside world without giving internal detail about those methods and data.

Encapsulation

Encapsulation refers to the mechanism that allow each object to have its own data and methods. It is an inherent in the concept of an abstract data type. Object-oriented programming provides you framework to place the data and the relevant functions together in the same object.

Object-oriented languages provide more powerful and flexible encapsulation mechanisms for restricting interactions between components. When used carefully, these mechanisms allow the software developers to restrict the interactions between components to those that are required to achieve the desired functionality

Inheritance 

Inheritance mainly helps in code re usability. It is the process of forming a new class from an existing class. The existing class is called as the super class /base class and the new class is called a child class/ derived class.
This is a very important concept of object oriented programming since this feature helps to reduce the code size.

Polymorphism

The ability to use an operator or function in different ways in other words giving different meaning or functions to the operators or functions is called polymorphism.

Polymorphism refers to the capability of having methods with the same names and parameter types exhibit different behavior depending on the receiver. In other words, you can send the same message to two different objects and they can respond in different ways.

Overloading

The concept of overloading is also a branch of polymorphism. When the exiting operator or function is made to operate on new data type it is said to be overloaded.

More generally, the capability of using names to mean different things in different contexts is called overloading. This also includes allowing two methods to have the same name but different parameters types, with different behavior depending on the parameter types.

Method overriding

Method overriding, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super classes or parent classes. The implementation in the subclass overrides (replaces) the implementation in the super class by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class.

I guess you had some knowledge about Object Oriented programming in C++ from this post. I wanted to start from the OOP basics because up to this post I described you C++ only as a procedural language where you found methods everywhere.  

from the next post onward, I'll describe how to apply OOP in C++ starting from simple programs as I always did :)