Phonebook Sample in C++ Using Objects

akhtar727's Avatar author of Phonebook Sample in C++ Using Objects
Making a Phone Book application in C++ to understand the OOPs features of the C++ language..
Making a Phone Book application in C++ is interesting; because it lets you learn the language practically. Making sample applications in any programming language is an interesting job. And this is perhaps the best approach to learning any programming language.

As a programmer, your goal is to master the programming skills so that you can develop a software application. The more you write programs, the more new good habits you’ll develop. Besides this, you’ll also be able to practice some of the language features by repeatedly using them in your program.

The focus of this article is to show you how the Phone Book application is developed in C++ using the OOP principles. You’ll know about the features of the Phone Book application. You’ll also learn how to effectively implement the OOP principles in your program. The source code is explained properly.

This article will take you through the following.
  1. Overview and features.
  2. Implementing the OOP principles.
  3. Design and coding: how the coding was done.
Features of my Phonebook application

Before diving into technical details, an overview of the sample is necessary. First of all, this is not a complete big project. Instead, this is a sample project. Sample project means a demo project, a small application that demonstrates how a full-working project of this type can be developed. This small sample is developed so that you can learn certain features of the C++ programming language.

This is a sample console program in C++. That is, this is a Console program, not GUI.
As the name implies, Phonebook is an application that allows you to perform the very basic phone book operations such as storing, showing, deleting and searching contacts. This application lets you perform the necessary operations quickly. So it can be pretty useful in real life situations. The features are explained as follows.
  • Show contact Details: You can see the list of the names along with their phone numbers using this feature. This feature shows you the contact list. All the contacts are shown one by one in a list.
  • Add contacts: This feature allows you to add a new contact to the contacts-list of the Phonebook application. Adding new contacts is very easy. You just need to enter the contact’s name and phone number. A message will be shown upon successful addition of any contacts.
  • Validations: This feature ensures that you make only the valid entries. It does not allow you to add a contact with incorrect information. For example, you cannot add a mobile number of 100 digits.
  • Edit contacts: The existing contacts can be edited using this feature. You can edit the existing contacts and save them to the contacts-list.
  • Deleting contacts: Contacts can be deleted from the contacts-list. You can delete a contact from the main menu.
  • Search contacts: The searching facility lets you search a contact by name. You can search a contact by entering the contact’s name. If the contact is not found, an appropriate message is shown.
NOTE: This sample does not include the concepts of file-programming, database-programming and Windows API programming. So when the application is closed, all the contacts are vanished. As I already mentioned that this is not a full-working sample, this doesn’t include all the features that an ideal Phonebook application should have. In fact, as a learner, this is your task to develop this sample to the further stage. There’s a huge developmental scope.

Download the complete cpp code here.

Implementing the OOP principles



C++ is an object-oriented programming language. The main principles of OOP are encapsulation, polymorphism and inheritance. The primary advantage of OOP is that it significantly reduces the coding complexity. Generally, this is noticeable in large programs. Complexity is reduced in several ways. One way is by hiding the implementation details inside a class.

One of the best methods to programming is to use objects. Give some meaningful names to the objects and imagine them as real-life objects such as car, pen, ball, pencil etc. Then use values and methods for them. More specifically, you can set color, size, height etc. to a real-life object, and you can specify what actions those objects will perform. This is how programs are written using C++.

Instead of imagining anything as a huge collection of technical stuff, this can be far easier for human beings to imagine something as an object. In simple words, when we say “car”, the picture of a real car comes in our mind. It is extremely easy to imagine it as an object, whereas it’s extremely difficult to imagine a “car” as a gigantic collection of all the scientific, technical, electrical and mechanical stuff. In other words, it is difficult to imagine how it is developed. In the same way, C++ hides certain things. It allows you to hide a certain aspect of the entire development. So instead of knowing how it is developed, you need to focus on how to implement. So the class designer will design and write the classes. As a programmer, you simply need to learn how to implement the classes in your program.

Designing the class



The name of the class is “contact”. There are two data members – name and mob. Examine the class below to see the data members and member functions used in this class of the Phonebook project.
Code:
class contact
{
    string name;
    string mob;
        
    public:
        contact(): name(""), mob("")
        {}
        bool show();
        bool show(string search_term);
        bool name_exists(string tname);
        bool add(string new_name, string new_mob);
        bool edit(string);
        bool erase(string new_name);
};
Creating an array of objects

An array of objects of the ‘contact’ class is created inside the main function. The following statement creates an array of objects.

contact person[100];

Person is the name of the object. A real-life meaningful name has been given to this object so that this C++ object looks like a real life objects. Thus it becomes easier to understand and write the code. This also increases the readability of the code.

100 objects are created. So you cannot add more than hundred contacts to the contacts-list of the Phonebook application. You may use dynamic memory allocation to creat objects as per your requirements. This also saves memory space. And the program becomes light.

Designing a menu-driven GUI

A console program is significantly less user-friendly than a GUI program. This why, a menu has been added to the program so that it becomes more user-friendly to the users of this application. The menu is as follows.
  • 0. Show contacts.
  • 1. Add contact.
  • 2. Edit contact.
  • 3. Delete contact.
  • 4. Search contact.
  • 5. Quit
Consider the following code.
Code:
cout << "0. Show contacts" << endl
        << "1. Add Contact" << endl
        << "2. Edit Contact" << endl
        << "3. Delete Contact" << endl
        << "4. Search" << endl
        << "5. Quit" << endl << endl
        << "Your choice...";
        cin >> choice;
So if the user presses 0, the contacts are shown. If the user presses 1, they can add a contact. In this way, the program becomes relatively more user-friendly.

Showing contacts

The following code shows all the contacts from the contacts-list. Examine the below code to understand how it works.
Code:
//This block of code resides inside the main function
cout << "Showing Contacts" << endl;
                printline('-', 20);
                
                for(i=0; i<100; i++)
                    if(person[i].show())
                        flag = 1;
                
                if(!flag)
                    cout << "No contacts found!" << endl;

//This block of code resides inside the class
bool show()
        {
            if(name != "")
            {
                cout << name << "\t" << mob << endl;
                return 1; //Indicates success
            }
            else
                return 0; //Indicates failure
        }
Adding contacts

The following code adds a new contact to the contacts-list of the Phonebook application.
Code:
//The following code resides in the main function.
cout << "Add New Contact\t\t\t\tpress $ to cancel" << endl;
                printline('-', 20);
                counter = 0;
                
                //Loop until correct name and mobile number are entered
                do
                {
                    flag = 0;
                    if(counter)
                        cout << "Try again\t\t\t\tpress $ to cancel" 
						<< endl;
						
                    //counts how many times the do-while loop executes
					counter++; 
                        
                    cout << "Name: "; cin >> temp_name;
                    
                    //Cancel operation
                    if(temp_name=="$")
                    {
                        cancel_flag = 1;
                        break;
                    }
                    cout << "Mobile No.: "; cin >> temp_mob;
                    
                    //Cancel operation
                    if(temp_mob=="$")
                    {
                        cancel_flag = 1;
                        break;
                    }
                    
                    //Check whether name exists
                    for(i=0; i<100; i++)
                        if(person[i].name_exists(temp_name))
                        {
                            cout << "The name you entered is already there" 
							"in the phonebook, enter a different name." 
							<< endl;
                            flag = 1;
                            break;
                        }
                    
                }while(!name_valid(temp_name) || 
								flag ||
						!mob_valid(temp_mob));
                
                if(cancel_flag)
                {
                    system("cls");
                    break;
                }
            
                
                //This code adds the contact to phonebook    
                for(i=0; i<100; i++)
                    if(person[i].add(temp_name, temp_mob))
                    {
                        cout << "Contact added successfully!" << endl;
                        flag = 1;
                        break;
                    }
                
                if(!flag)
                    cout << "Memory full! Delete some contacts first." 
					<< endl;

//The following code resides in the class
bool add(string new_name, string new_mob)
        {
            if(name=="")
            {
                name = new_name;
                mob = new_mob;
                return 1; // Success
            }
            else
                return 0; // Failure
    
        }
The above code checks whether the user has entered a correct name and a correct mobile number. If the user has not entered the correct name and correct mobile number, the program prompts the user to enter valid a name and a valid mobile number. After that, it checks whether the name entered is already there in the phonebook. The program prompts the user to enter another name. The user always has the option to cancel the operation.

If there are already 100 contacts, a message will be shown indicating that the memory is full. In this case, the user has to delete some contacts in order to enter new contacts. 100 is the limit as the array size is 100. You have two options so that the program can hold more contacts. Either change the array size or use dynamic memory allocation.

Editing a contact

The following code edits an existing contact. It edits both – name and mobile number.
Code:
//The following code resides in the main function
cout << "Enter a contact name to edit:" 
				"\t\t\t\tpress $ to cancel\n";
				 cin >> temp_name;
                
                //Cancel Operation
                if(temp_name=="$")
                {
                    system("cls");
                    break;
                }
                
                for(i=0; i<100; i++)
                    if(person[i].edit(temp_name))
                    {
                        cout << "Edited Successfully!" << endl;
                        flag = 1;
                        break;
                    }
                
                if(!flag)
                    cout << "Contact name not found!" << endl;
                


//The following code resides in the class
bool contact :: edit(string new_name)
{
    string new_mob;
    if(new_name==name)
    {
        cout << "Enter new name: "; cin >> new_name;
        cout << "Enter new mobile no: "; cin >> new_mob;
        
        name = new_name;
        mob = new_mob;
        return 1;
    }
    else
        return 0;
}
Removing a contact

The following code removes a contact from the contacts-list in the Phonebook application.
Code:
// The following code resides in the main function.
do
                {
                    if(counter)
                        cout << "Try again" << endl;
                    counter++;
                    cout << "Enter a contact name to delete:" 
					"\t\t\tpress $ to cancel\n"; 
					cin >> temp_name;
                
                    //Cancel Operation
                    if(temp_name=="$")
                    {
                        system("cls");
                        break;
                    }
                
                
                    //Final Confirmation
                    for(i=0; i<100; i++)
                    if(person[i].name_exists(temp_name))
                    {
                        flag = 1;
                        cout << "Are you sure you want to delete? (1/0)" 
						<< endl;
                        int yes;
                        cin >> yes;
                        if(!yes)
                        {
                            system("cls");
                            cancel_flag = 1;
                        }
                        break;
                    }
                
                    if(!flag)
                        cout << "Contact name not found!" << endl;
                    
                    if(cancel_flag)
                        break;
                
                    // This code deletes the contact
                    if(flag)
                    {
                        for(i=0; i<100; i++)
                            if(person[i].erase(temp_name))
                            {
                                cout << "Deleted successfully!" << endl;
                                break;
                            }
                    }
                    
                }while(!flag);

// The following code resides in the class
bool erase(string new_name)
        {
            if(new_name==name)
            {       
                name = "";
                mob = "";
                return 1;
            }
            else
                return 0;
        }
Searching for a contact

The following code searches for a contact.
Code:
// The following code resides in the main function.
do
                {
                    if(counter)
                        cout << "Try again" << endl;
                    counter++;
                    cout << "Search a name: \t\t\t\tpress $ to cancel\n";
					 cin >> temp_name;
                
                    //Cancel Operation
                    if(temp_name=="$")
                    {
                        system("cls");
                        break;
                    }
                
                    for(i=0; i<100; i++)
                        if(person[i].show(temp_name))
                        {
                            flag = 1;
                            break;
                        }
    
                    if(!flag)
                        cout << "Contact name not found" << endl;
                }while(!flag);

// The following code resides in the class
bool show(string search_term)
        {
            if(search_term == name)
            {
                cout << name << "\t" << mob << endl;
                return 1;
            }
            else
                return 0;
        }
The printline() function

The printline() function prints a line. You can specify the size and the character for drawing the line.
Code:
void printline(char ch, int size)
{
    for(int i=0; i<size; i++)
        cout << ch;
    cout << "\n";
}
Validations

Two functions have been used for validations. One is name_valid(), another is mob_valid. The first one checks whether the name is valid, while the second function checks whether the mobile number is valid.
Code:
bool name_valid(string tname)
{
    if(tname.size()>20)
    {
        cout << "Invalid Name!\nEnter a name within 20 characters!" 
		<< endl;
        return 0;
    }
    else if(tname == "")
    {
        cout << "Invalid Name!\nName cannot be blank!" << endl;
        return 0;
    }
    else
        return 1;
}

//mobile number validation
bool mob_valid(string tmob)
{
    if(tmob.size()>13 || tmob.size()<10)
    {
        cout << "Invalid mobile no.\nEnter a no." 
		"between 10 and 13 digits" << endl;
        return 0;
    }
    else if(tmob == "")
    {
        cout << "Invalid mobile no.\nMobile" 
		"no cannot be blank" << endl;
        return 0;
    }
    else
        return 1;
}
Attached Files
File Type: zip phonebook.cpp.zip (2.5 KB, 33 views)
shabbir like this