C++ 1
C++ 1
C++ 1
Developments in software technology continued to be dynamic. New tools and techniques were
announced in quick succession. This forced software engineers and industry to continuously
look for new approaches to software design and development, and they were becoming more and
more critical in view of the increasing complexity of software systems as well as the highly
competitive nature of the industry. These rapid advances appeared to have created a situation of
crisis within the industry. The following issues needed to be addressed to face the crisis:
• How to design system with open interfaces? - A public standard for connecting hardware to
hardware and software to software. With regard to hardware, it implies that there is more than
one brand of product that can be hooked up to the device with the open interface.
• Data and functions (which are called “methods” in object-oriented programming) are
encapsulated, or contained, within a class. Individual objects are created as an instance of a
class.
• The program tells an object to perform tasks by passing messages to it.
• Such a message consists of an instruction to execute one of the class’s methods. The class
method then manipulates the data (which is part of the object itself ).
• Many modern programming languages now support OOP.
• An object is defined by two terms: attributes and behaviors. If you look at a person and
• visualize him/her as an object, you will find that a person has attributes, such as, eye color,
• age, height, and so on. A person also has behaviors, such as walking, talking, breathing,
• and so on. In its basic definition, an object is an entity that contains both data and
• behavior. The word both is the key difference between the more traditional programming
• methodology, procedural programming, and OOP
Object Oriented Programming
• The major motivating factor in the invention of object-oriented approach is to remove some
of the flaws encountered in the procedural approach. OOP treats data as a critical element in
the program development and does not allow it to flow freely around the system. It ties data
more closely to the function that operate on it, and protects it from accidental modification
from outside function. OOP allows decomposition of a problem into a number of entities
called objects and then builds data and function around these objects.
• The data of an object can be accessed only by the function associated with that object.
• However, a function of one object can access the functions of other objects.
Features Object Oriented Programming
Some of the features of object oriented programming are:
• Emphasis is on data rather than procedure.
or explanation. Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight, and cost, and functions operate on these attributes.
• The attributes are some times called data members because they hold information. The
functions that operate on these data are sometimes called methods or member function.
• Abstraction serves as a template for subclasses to fully implement the methods.
Concepts of OOP
Inheritance
• You can reuse classes and reuse the code that is written for the members of a class by
taking advantage of inheritance. Inheritance allows you to create a new class that is based
on an existing class.
• To use inheritance, you create a new class (called the derived class) that contains the
members of the original class (called the base class).
• You can then modify the derived class by adding new members that allow it to behave in
new ways. You can also redefine methods that are inherited from the base class if they do not
meet your exact needs in the derived class.
• For example, if you have an existing Vehicle class, you could derive a new class named
Automobile from the Vehicle class. You could also derive a TaxiCab class, a Motorcycle
class, or a GoKart class from the Vehicle class. In C++, any class can serve as a base class.
Concepts of OOP
Inheritance
• Inheritance is the process by which objects of one class acquired the properties of objects of
another classes. It supports the concept of hierarchical classification.
• Inheritance represents an IS-A relationship
• For example, the bird, ‘robin’ is a part of class ‘flying bird’ which is again a part of the
class ‘bird’. The principal behind this sort of division is that each derived class shares
common characteristics with the class from which it is derived.
• In OOP, the concept of inheritance provides the idea of reusability. This means that we can
add additional features to an existing class without modifying it. This is possible by
deriving a new class from the existing one. The new class will have the combined feature of
both the classes.
• The real appeal and power of the inheritance mechanism is that it allows the programmer to
reuse a class i.e almost, but not exactly, what he wants, and to tailor the class in such a way
that it does not introduce any undesirable side-effects into the rest of classes.
Concepts of OOP
• Inheritance example
Concepts of OOP
Polymorphism
• Polymorphism is another important OOP concept.
• Polymorphism, a Greek term, means the ability to take more than one form.
• An operation may exhibit different behavior in different instances. The behavior depends
upon the types of data used in the operation. For example, consider the operation of addition
for two numbers, the operation will generate a sum. If the operands are strings, then the
operation would produce a third string by concatenation. The process of making an operator
to exhibit different behaviors in different instances is known as operator overloading.
Concepts of OOP
• Polymorphism plays an important role in allowing objects having different internal
structures to share the same external interface. This means that a general class of operations
may be accessed in the same manner even though specific action associated with each
operation may differ. Polymorphism is extensively used in implementing inheritance.
Dynamic Binding
• Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time. It is associated with polymorphism and
inheritance. A function call associated with a polymorphic reference depends on the
dynamic type of that reference.
• Consider the procedure “draw” by inheritance, every object will have this procedure. Its
algorithm is, however, unique to each object and so the draw procedure will be redefined in
each class that defines the object. At run-time, the code matching the object under current
reference will be called.
Concepts of OOP
Message Passing
• An object-oriented program consists of a set of objects that communicate with each other.
The process of programming in an object-oriented language, involves the following basic
steps:
• 1. Creating classes that define object and their behavior,
• An object has a life cycle. They can be created and destroyed. Communication with an
object is feasible as long as it is alive
Benefits of OOP
• OOP offers several benefits to both the program designer and the user. Object-Orientation
contributes to the solution of many problems associated with the development and quality
of software products. The technology promises greater programmer productivity, better
quality of software and lesser maintenance cost. The principal advantages are:
• Through inheritance, we can eliminate redundant code extend the use of existing
classes.
• We can build programs from the standard working modules that communicate with
one another, rather than having to start writing the code from scratch. This leads to
saving of development time and higher productivity.
• The principle of data hiding helps the programmer to build secure program that can
not be invaded by code in other parts of a programs.
• It is possible to have multiple instances of an object to co-exist without any
interference.
• It is possible to map objects in the problem domain
• It is easy to partition the work in a project based on objects.
• The data-centered design approach enables us to capture more detail of a model
• Object-oriented system can be easily upgraded from small to large system.
• Message passing techniques for communication between objects makes to interface
descriptions with external systems much simpler.
• Software complexity can be easily managed.
Limitations of OOP
• Size: Object Oriented programs are much larger than other programs. In the early days of
computing, space on hard drives, floppy drives and in memory was at a premium. Today we
do not have these restrictions.
• Effort: Object Oriented programs require a lot of work to create. Specifically, a great deal
of planning goes into an object oriented program well before a single piece of code is ever
written. Initially, this early effort was felt by many to be a waste of time. In addition,
because the programs were larger coders spent more time actually writing the program.
• Speed: Object Oriented programs are slower than other programs, partially because of their
size. Other aspects of Object Oriented Programs also demand more system resources, thus
slowing the program down.
• The benefits of OOP may be realized after a long period.
• Requires intensive testing procedures.
Object Based Language vs OOP language
• Object-oriented programming is not the right of any particular languages. Like structured
programming, OOP concepts can be implemented using languages such as C and Pascal.
However, programming becomes clumsy and may generate confusion when the programs
grow large. A language that is specially id designed to support the OOP concepts makes it
easier to implement them.
• The languages should support several of the OOP concepts to claim that they are
object-oriented. Depending upon the features they support, they can be classified into the
following two categories:
• 1. Object-based programming languages, and
• 2. Object-oriented programming languages.
• Object-based programming is the style of programming that primarily supports
encapsulation and object identity. Major feature that are required for object based
programming are:
• Data encapsulation
• Data hiding and access mechanisms
• Automatic initialization and clear-up of objects
• Operator overloading
Object Based Language vs OOP language
• Languages that support programming with objects are said to the objects-based
programming languages. They do not support inheritance and dynamic binding.. Object
based programming language follows all the features of OOPs except Inheritance.
JavaScript , Ada, and VBScript are examples of object based programming languages.
• Object-oriented programming language incorporates all of object-based programming
features along with two additional features, namely, inheritance and dynamic binding.
Object-oriented programming can therefore be characterized by the following statements:
• Object-based features + inheritance + dynamic binding
Application of OOP
• OOP has become one of the programming buzzwords today. There appears to be a great
deal of excitement and interest among software engineers in using OOP. Applications of
OOP are beginning to gain importance in many areas. The most popular application of
object-oriented programming, up to now, has been in the area of user interface design such
as window. Hundreds of windowing systems have been developed, using the OOP
techniques.
• Real-business system are often much more complex and contain many more objects with
complicated attributes and method. OOP is useful in these types of application because it
can simplify a complex problem. The promising areas of application of OOP include:
• Real-time systems
• • Simulation and modeling
• • Object-oriented databases
• • Hypertext, Hypermedia, and expertext
• • AI and expert systems
• • Neural networks and parallel programming
• • Decision support and office automation systems
• Computer Integrated Manufacturing (CIM)/CAM/CAD systems
History of C++
• C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell
Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s.
• Stroustrup, an admirer of Simula67 and a strong supporter of C, wanted to combine the best of both the
languages and create a more powerful language that could support object-oriented programming
features and still retain the power and elegance of C. The result was C++. Therefore, C++ is an
extension of C with a major addition of the class construct feature of Simula67.
• Since the class was a major addition to the original C language, Stroustrup initially called the new
language ‘C with classes’. However, later in 1983, the name was changed to C++. The idea of C++
comes from the C increment operator ++, thereby suggesting that C++ is an augmented version of C.
• C+ + is a superset of C. Almost all c programs are also C++ programs. However, there are a few minor
differences that will prevent a c program to run under C++ complier.
• The most important facilities that C++ adds on to C care classes, inheritance, function overloading and
operator overloading. These features enable creating of abstract data types, inherit properties from
existing data types and support polymorphism, thereby making C++ a truly object-oriented language.
History of C++
• One of the most popular programming languages among computer programmers is C. About a decade
ago it was extended with object-oriented elements and was then called C++.
• The majority of applications running on Microsoft Windows, Mac OS and Linux are written in C++.
• Microsoft has introduced C# (speak: C sharp) which is a popular variant of C++ that has been
integrated in the Microsoft.Net Framework
• Java is also a subset of C++
Summary
• Software technology has evolved through a series of phases during the last five decades.
• POP follows top-down approach where problem is viewed as sequence of task to be performed and
functions are written for implementing these tasks.
• POP has two major drawbacks:
1. Data can move freely around the program.
2. It does not model very well the real-world problems.
• OOP was inventing to overcome the drawbacks of POP. It follows down -up approach.
• In OOP, problem is considered as a collection of objects and objects are instance of classes.
• Data abstraction refers to putting together essential features without including background details.
• Inheritance is the process by which objects of one class acquire properties of objects of another class.
• Polymorphism means one name, multiple forms. It allows us to have more than one function with the
same name in a program.
• Dynamic binding means that the code associated with a given procedure is not known until the time of the
run time.
• Message passing involves specifying the name of the object, the name of the function and the information
to be sent.
• C++ is a superset of C language.
• C++ ads a number of features such as objects, inheritance, function overloading and operator overloading
to C.
• C++ supports interactive input and output features and introduces anew comment symbol // that can be
used for single line comment.
• Like C programs, execution of all C++ program begins at main() function.
Keywords
Keywords
Structure of a program
• C++ is a versatile language for handling very large programs; it is suitable for virtually any
programming task including development of editors, compilers, databases, communication
systems and any complex real life applications systems.
• Since C++ allows us to create hierarchy related objects, we can build special object-oriented
libraries which can be used later by many programmers.
• While C++ is able to map the real-world problem properly, the C part of C++ gives the
language the ability to get closed to the machine-level details.
• C++ programs are easily maintainable and expandable. When a new feature needs to be
implemented, it is very easy to add to the existing structure of an object.
• • It is expected that C++ will replace C as a general-purpose language in the near future.
Structure of a c++ program
#include<iostream>
using namespace std;
int main()
{
cout<<” c++ is better than c \n”;
return 0;
}
Structure of a program
#include <iostream>
• We have used the following #include directive in the program:
#include <iostream>
• The #include directive instructs the compiler to include the contents of the file enclosed within angular
brackets into the source file. The header file <iostream>should be included at the beginning of all
programs that use input/output statements.
using namespace std
-The next line (using namespace std;) instructs the compiler to use the std namespace.You can think of a
namespace as a container that holds various program elements. The std namespace contains
everything C++ programs need to use the Standard C++ library. The Standard C++ library adds
functionality to the C++ programming language.
-For example, this program needs to use the std namespace to have access to cout and endl. Notice that this
line ends with a semicolon(;). In fact, all C++ statements end with a semicolon. The reason the previous
line,#include <iostream>, does not end with a semicolon is that it is a preprocessor
directive, not a C++ statement.
NB: If the statement is not included then the code then a some statements will not be recognised e.g
cout, endl as they will require a scope resolution operator i.e
# include<iostream>
int main()
{
std::cout<<” c++ is better than c ”<<std::endl;
return 0;
}
Structure of a program
Comments
• C++ introduces a new comment symbol // (double slash). Comment start with a double
slash symbol and terminate at the end of the line. A comment may start anywhere in the
line, and whatever follows till the end of the line is ignored. Note that there is no closing
symbol.
• The double slash comment is basically a single line comment. Multiline comments can be
written as follows:
• // This is an example of
• The C comment symbols /*,*/ are still valid and are more suitable for multiline comments.
The following comment is allowed:
/* This is an example of
C++ program to illustrate some of its features
*/
• Curly brackets { } indicate the beginning and end of a function, which can also be called the
function's body. The information inside the brackets indicates what the function does when
executed.
• The entry point of every C++ program is main(), irrespective of what the program does.
Structure of a program
return type of main()
In C++, main () returns an integer value to the operating system. Therefore, every main () in
C++ should end with a return (0) statement; otherwise a warning an error might occur. Since
main () returns an integer type for main () is explicitly specified as int.
NB: The default return type for all functions in C++ is int.
Output operator
• . The statement
cout<<”C++ is better than C.”;
• Causes the string in quotation marks to be displayed on the screen. This statement introduces two new
C++ features, cout and <<. The identifier cout(pronounced as C out) is a predefined object that
represents the standard output stream in C++. Here, the standard output stream represents the screen. It
is also possible to redirect the output to other output devices. The operator << is called the insertion or
put to operator.
• -in C++, streams are used to perform input and output operations.
• -In most program environments, the standard default output destination is the screen. In C++, cout is
the stream object used to access it.
• -In C++, the semicolon is used to terminate a statement. Each statement must end with a semicolon. It
indicates the end of one logical expression.
The \n is known as an escape character which instructs the compiler to jump a line after
printing a message. There are other escape codes such as
\t for a tab sequence
\b for a backspace
Structure of a program
Multiple New Lines
-Using a single cout statement with as many instances of \n as your program requires
will print out multiple lines of text.
#include <iostream>
int main()
return 0;
}
Structure of a program
Rearrange the code blocks to form a valid C++ program:
int main() {
#include <iostream>
=======================================================
New Line
• The cout operator does not insert a line break at the end of the output. One way to print two
lines is to use the endl manipulator, which will put in a line break.
#include <iostream>
int main(){
return 0; }
Accepting user input
• Let us consider a slightly more complex C++ program. Assume that we should like to read
two numbers from the keyboard and display their average on the screen. C++ statements to
accomplish this is shown in the program below:
#include<iostream> // include header file
using namespace std;
int main()
{
float number1, number2,sum, average;
cin >> number1; // Read Numbers
cin >> number2; // from keyboard
sum = number1 + number2;
average = sum/2;
cout << ”Sum = “ << sum << endl;
cout << “Average = “ << average << endl;
return 0;
} //end of example
The output would be:
Enter two numbers: 6.5 7.5
Sum = 14
Average = 7
Accepting user input
• The program uses four variables number1, number2, sum and average. They are declared as
type float by the statement.
• float number1, number2, sum, average;
• All variable must be declared before they are used in the program.
Input Operator
• The statement
• cin >> number1;
• Is an input statement and causes the program to wait for the user to type in a number. The
number keyed in is placed in the variable number1. The identifier cin (pronounced ‘C in’) is
a predefined object in C++ that corresponds to the standard input stream.
• Here, this stream represents the keyboard. The operator >> is known as extraction or get
from operator. It extracts (or takes) the value from the keyboard and assigns it to the
variable on its right . This corresponds to a familiar scanf() operation. Like <<, the operator
>> can also be overloaded.
Cascading the input and output operators
• We have used the insertion operator << repeatedly in the last two statements for printing
results.
• The statement
cout << “Sum = “ << sum << “\n”;
• First sends the string “Sum = “ to cout and then sends the value of sum. Finally, it sends the
newline character so that the next output will be in the new line. The multiple use of << in
one statement is called cascading. When cascading an output operator, we should ensure
necessary blank spaces between different items. Using the cascading technique, the last two
statements can be combined as follows:
cout << “Sum = “ << sum << “\n” << “Average = “ << average << “\n”;
• This is one statement but provides two line of output. If you want only one line of output,
the statement will be:
cout << “Sum = “ << sum << “,”
<< “Average = “ << average << “\n”;
• The output will be:
• Sum = 14, average = 7
We can also cascade input operator >> as shown below:
cin >> number1 >> number2;
• The values are assigned from left to right. That is, if we key in two values, say, 10 and 20,
then 10 will be assigned to munber1 and 20 to number2.
Cascading the input and output operators
• We have used the insertion operator << repeatedly in the last two statements for printing results.
• The statement
cout << “Sum = “ << sum << “\n”;
• First sends the string “Sum = “ to cout and then sends the value of sum. Finally, it sends the newline
character so that the next output will be in the new line. The multiple use of << in one statement is
called cascading. When cascading an output operator, we should ensure necessary blank spaces
between different items. Using the cascading technique, the last two statements can be combined as
follows:
cout << “Sum = “ << sum << “\n” << “Average = “ << average << “\n”;
• This is one statement but provides two line of output. If you want only one line of output, the statement
will be:
cout << “Sum = “ << sum << “,”
<< “Average = “ << average << “\n”;
• The output will be:
• Sum = 14, average = 7
We can also cascade input operator >> as shown below:
cin >> number1 >> number2;
• The values are assigned from left to right. That is, if we key in two values, say, 10 and 20, then 10 will
be assigned to munber1 and 20 to number2.
Accepting input for string types
• We normally use the cin >> for a string character eg Thompson, but there are situations
where you
may want to accept a string that contains spaces eg Thompson Marufu
• In such a case we use the getline() method e.g
string name;
cout<<“Enter the full name”<<endl;
getline(cin,name);
NB: Such variables that contain spaces should be prompted first before other variables as an
anomaly can occur in the program flow
Accepting input for string types: string class
// To use strings.
#include <iostream> // Declaration of cin, cout
#include <string> // Declaration of class string
using namespace std;
int main()
{
// Defines four strings:
string prompt("What is your name: "),
name, // An empty
line( 40, '-'), // string with 40 '-'
total = "Hello "; // is possible!
cout << prompt; // Request for input.
getline( cin, name); // Inputs a name in one line
total = total + name; // Concatenates and
// assigns strings.
cout << line << endl // Outputs line and name
<< total << endl;
cout << " Your name is " // Outputs length
<< name.length() << " characters long!" << endl;
cout << line << endl;
return 0;
}
Accepting input for string types: string class
• Several classes are defined in the C++ standard library. These include stream classes for input and
output, but also classes for representing strings or handling error conditions.
• Each class is a type with certain properties and capacities. As previously mentioned, the properties of a
class are defined by its data members and the class’s capacities are defined by its methods. Methods
are functions that belong to a class and cooperate with the members to perform certain operations.
Methods are also referred to as member functions.
• Creating Objects
An object is a variable of a class type, also referred to as an instance of the class. When an
object is created, memory is allocated to the data members and initialized with suitable
values.
• Example: string s("I am a string");
In this example the object s, an instance of the standard class string (or simply a string), is defined and
initialized with the string constant that follows. Objects of the string class manage the memory space
required for the string themselves. In general, there are several ways of initializing an object of a class.
A string can thus be initialized with a certain number of identical characters, as the example on the
opposite page illustrates.
Accepting input for string types: string class
• Calling Methods
All the methods defined as public within the corresponding class can be called for an object. In contrast to
calling a global function, a method is always called for one particular object. The name of the object
precedes the method and is separated from the method by a period.
• Example: s.length(); // object.method();
The method length() supplies the length of a string, i.e. the number of characters in a string. This results in a
value of 13 for the string s defined above.
• Classes and Global Functions
Globally defined functions exist for some standard classes. These functions perform certain operations for
objects passed as arguments. The global function getline(), for example, stores a line of keyboard input in a
string.
• Example: getline(cin, s);
The keyboard input is terminated by pressing the return key to create a new-line character,'\n', which is not
stored in the string.
• Create a C++ program that defines a string containing the following charactersequence:
I have learned something new again!
and displays the length of the string on screen. Read two lines of text from the keyboard.
Concatenate the strings using " * “ to separate the two parts of the string. Output the new string on
screen.
Accepting input for string types: string class
#include <iostream> // Declaration of cin, cout
#include <string> // Declaration of class string
int main()
return 0;
}.
Datatypes and Variables
Datatypes can be primitive or reference types. The following are examples of primitive
datatypes
• they cannot start with a number but can start with an underscore character or a letter
• int myInt;
• int _my32Int;
Variable Assignation
• Syntax
• we can assign more than one variable of the same type in one line
• C++ is case-sensitive, which means that an identifier written in uppercase is not equivalent
to another one with the same name in lowercase.
• For example, myvariable is not the same as MYVARIABLE and not the same as
MyVariable. These are three different variables.
• Choose variable names that suggest the usage, for example: firstName, lastName.
• name3_var
• salary
• &*^var
Inbuilt Functions
• These are functions that are found within the compiler
1.) setprecision() – this function is a member of the <iomanip> header filer. It is a
special C++ function that can control(manipulate) how data is displayed.
#include <iostream>
#include <iomanip>
using namespace std;
int main( ) {
double value = 3.14159;
cout << value << endl; //3.14159
cout << setprecision(1) << value << endl;//3
cout << setprecision(2) << value << endl;//3.1
cout << setprecision(3) << value << endl;//3.14
cout << setprecision(4) << value << endl;//3.142
cout << setprecision(5) << value << endl;//3.1416
cout << setprecision(6) << value << endl;//3.14159
return 0;
}
• In the preceding code sample, setprecision is a manipulator that controls how the floating
point value should be formatted. The setprecision manipulator requires one integer argument
that
specifies the maximum number of digits to display including both those before and those after the
decimal point. For example, the C++ code double value = 3.14159;
cout << setprecision(3) << value << endl;
produces the following output: 3.14.
Inbuilt Functions
2. setw(n)- it is a manipulator function which sets n spaces when displaying the output
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
string n=“Samuel”, y= “Furusa”;
cout<<n<<setw(20)<<y<<endl;
return 0;
}
This will print variable n and leave 20 spaces then print y
3. pow(number,n) = raises a number to the power of n. It is part of the <math.h> header file
#include <iostream>
#include <math.h>
using namespace std;
int main(){
int result = pow(2,3);
cout<<result<<endl;
return 0;
}
Inbuilt Functions
4. tolower() and toupper() – these functions set a character to lower and uppercase
char sample1 = 'A';
char sample2 = 'a';
char result1, result2;
result1 = tolower(sample1);
result2 = toupper(sample2);
Review Questions
Structures
Suppose you are writing an inventory program for a warehouse. The warehouse is filled with
bins, each containing a bunch of parts. All the parts in a bin are identical, so you don't have to
In previous example we have used arrays for storing a groupof similar data types, but in this
example you have a mixed bag: two integers and a string. Instead of an array, you will use a
new data type called a structure. In an array, all the elements are of the same type and are
numbered. In a structure, each element, or member, is named and has its own data type.
• A structure is a data type that can hold several different values. Unlike an array, these
values don’t have to have the same type. Each item or field in the data structure has it own
name.
Structures
• The general form of a structure definition is:
struct structure-name {
member-type member-name; // Comment
member-type member-name; // Comment
member-type method(){
..
}
....
} object;
• For example, say you want to define a bin to hold printer cables. The
structure definition is:
struct bin {
char name[30]; // Name of the part
int quantity; // How many are in the bin
int cost; // The cost of a single part
} printer_cable_box;
Structures
• We can create an array of objects in structures
e.g
struct employee{
string name;
float age;
public:
void getdata(){
cout<<“enter name”<<endl;
cin>>name;
cout<<“enter age”<<endl;
cin>>age;
}
void putdata(){
cout<<name<<setw(10)<<age<<endl;
}
};
• The setw( 10) is an inbluilt method under the <iomanip> header file which creates a space
in between characters in this case we are instructing the compiler to move 10 spaces after
printing the name.
Structures
The identifier employee is a userdefined data type and can be used to create objects that relate
to different categories of employees e.g
employee manager[3]; //array of manager
employee foreman[15]; //array of foreman
employee worker[75]; //array of worker
Using concepts of structures write a program which captures Student details (Name,
IDNumber, Programme) for a specific number of students and then compute the degree class
based on the tables given above.
Structures
include<iomanip>
using namespace std;
struct Grade{
string name, reg, prog;
double score[4], aggregate=0; double level[4];
void setValues(int n){
cout<<"Enter details for Student "<<(n+1)<<endl;
cout<<"Enter reg"<<endl;
cin>>reg;
cout<<"Enter name"<<endl;
cin>>name;
cout<<"Enter programe"<<endl;
cin>>prog;
for(int i=0; i<4; i++){
cout<<"Enter score for level "<<(i+1)<<endl;
cin>>level[i];
if(i==0){
score[i]= level[i]*0.1;
aggregate+= score[i];
} else if(i==1){
score[i]= level[i]*0.2;
aggregate+= score[i]; }
else if(i==2){ Structures
score[i]= level[i]*0.3;
aggregate+= score[i];
} else if(i==3){
score[i]= level[i]*0.4; aggregate+= score[i];
} else{ cout<<"Invalid range"; }
}}
void output(){
cout<<reg<<setw(7)<<name<<setw(7)<<prog<<setw(7)<<level[0]<<setw(7)<<score[0]<<setw(7)<<level[1]<<setw(
7)<<score[1]<<setw(7)<<level[2]<<setw(7)<<score[2]<<setw(7)<<level[3]<<setw(7)<<score[3]<<setw(7)<<aggrega
te<<endl;
} };
int main() {
int n;
cout<<"Enter number of students"<<endl;
cin>>n;
Grade a[n]; //input
for(int i=0; i<n; i++){
a[i].setValues(i);
}
cout<<"Reg "<<setw(7)<<"Name"<<setw(7)<<"Prog"<<setw(7)<<"Level 1"<<setw(7)<<"Score"<<setw(7)<<"Level
2"<<setw(7)<<"Score"<<setw(7)<<"Level 3"<<setw(7)<<"Score"<<setw(7)<<"Level
4"<<setw(7)<<"Score"<<setw(7)<<"Aggregate"<<endl;
//input for(int i=0; i<n; i++){
a[i].output();
}
return 0;
}
Structures Question for practice
. Create a structure called Investment which contains the following members:
Variables
Item Data Type Description
In the above example Steve and Jordan are object declarations. Members can be kept in
any of the three accessibility modes private, public and protected. Members in the public
visibility mode of the class are accessible to the objects of the class whereas members in
the private accessibility mode are not accessible to the objects of the class. They are only
accessible inside the class to the member functions of the class.
Classes: Example
Classes
• Here, the keyword class specifies that we are using a new data type and is followed by the class name.
• The body of the class has three keywords namely :
• C++, the keywords private and public are called access specifiers.
• Private
Private data and functions can only be accessed from within the class itself and friends of the
class. The data hiding concept in C++ is achieved by using the keyword private. Data hiding is a
security measure is used to protect unauthorized users from performing any operation(read/write
or modify) on the data. The data declared under Private section are hidden and safe from
accidental manipulation. Though the user can use the private data but not by accident.
• Protected
Accessible in the same class, derived classes and friends of the class
• Public
These are accessible anywhere where the object is visible. There are less restrictions
imposed on the public modifier. The functions that operate on the data are generally public so
that they can be accessed from outside the class but this is not a rule that we must follow.
Classes
• Here, the keyword class specifies that we are using a new data type and is followed by the class name.
• The body of the class has three keywords namely :
• C++, the keywords private and public are called access specifiers.
• Private
Private data and functions can only be accessed from within the class itself and friends of the
class. The data hiding concept in C++ is achieved by using the keyword private. Data hiding is a
security measure is used to protect unauthorized users from performing any operation(read/write
or modify) on the data. The data declared under Private section are hidden and safe from
accidental manipulation. Though the user can use the private data but not by accident.
• Protected
Accessible in the same class, derived classes and friends of the class
• Public
These are accessible anywhere where the object is visible. There are less restrictions
imposed on the public modifier. The functions that operate on the data are generally public so
that they can be accessed from outside the class but this is not a rule that we must follow.
Classes
• The only difference between a structure and a class in C++ is that by default the members of
a class are private while by default the members of a structure are public.
• If labels are missing in a class by default all members are private and such a class will be
hidden from the outside world and does not serve any purpose
• Variables that are declared inside a class are referred to as data members and the function
are referred to as member functions. Member functions have access to private variables and
functions and can be accessed from outside.
Example
class Item{
public:
};
Classes
The name item becomes a new type identifier that can be used to declare instances of that class
type. Class Item has two private data members and two public member functions . The function
getdata() can be used to assign values to member fields number and cost while putdata() for
displaying values. The functions provide access to the data members from outside the class.
Data from the class cannot be accessed by any function that is not a member of the class Item
Creating objects
• Declaring of item does not define any objects but will specify what they contain. After creation
of a class we need to create variables of the class type just like any other built in type for e.g
Item x; //such statements creates memory for the x of type Item.
• We can also create more than one object in one statement :: Item x,y,z;
• The declaration of an object is similar to that of a variable of any basic type.
• We can create objects by placing their names immediately after the closing brace but this method is rarely
used:
class Item
{
.........
.........
} x,y,z;
Accessing Class members
Private members of a class can only be accessed through member functions of that class. The
main() cannot contain statements that access variables directly i.e number and cost from
object-name.function-name(actual-arguments);
x.getdata(100,75.5);
Which will assign two variables some values of the object x by implementing the getdata()
function
• A member function can be invoked only using an object of the same class therefore we
cannot directly call methods outside the class i.e getdata(100,75.5);
• We can no also initialise private members or protected members directly outside the class
i.e x.number =100 since they are indirectly accessible by public methods.
int x,y;
public:
int z;
};
int main(){
xyz p;
p.x=0; //illegal
p.z=10; //ok
return 0;
Using data in this manner defeats the idea of data hiding and should be avoided.
Defining function members
Member functions can be defined in two phases but both performing the same task
• Outside the class definition
Member functions that are declared inside a class have to be defined separately outside the
class. The definitions are much like normal functions
Syntax
function body
• The membership label class-name:: tells the compiler that the function function-name belong
to the class class-name which means the scope of the function is restricted to the class-name
specified in the header line.
• The symbol :: is called the scope resolution operator.
• With reference to the Item class members putdata() and getdata() may be defined as follows
Defining function members
number= a;
cost=b;
cout<<“Number:”<<number<<endl;
Cout<<“Cost: ”<<cost<<endl;
Member functions have some special characteristics that are often used in progam development
which are:
• Several classes can use the same function name and the membership label will resolve their
scope
• Member functions can access the private data of the class while a non-member function
cannot do so except for a friend function
• A member function can call another member function directly without using the dot operator
Inside the class defintion
• The second method involves defining the actual function inside the class
• When a member function is defined inside a class, we do not require to place a membership
label along with the function name. We use only small functions inside the class definition and
such functions are known as inline functions.
• In case of inline function the compiler inserts the code of the body of the function at the place
where it is invoked (called) and in doing so the program execution is faster but memory
penalty is there.
Inside the class defintion
class Item{
int number;
float cost;
public:
number= a;
cost= b;
void outdata(void){
cout<<number<<endl;
cout<<cost<<endl;
};
Types of members in a class
There are two types of members found within a class namely
I. Static
II. Instance
Static
• Data members and member functions of a class in C++, may be qualified as static. We can
have static data members and static member function in a class which are declared with the
static keyword
– Static data member
• It is generally used to store value common to the whole class. The static data
member differs from an ordinary data member in the following ways :
• (i) Only a single copy of the static data member is used by all the objects regardless
of the number of objects.
• (ii) It can be used within the class but its lifetime is the whole program.
• (iii) Does not require an object to be accessed instead it uses a scope resolution
opearator
Example creating an object using a pointer variable
class Circle{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Circle::Circle(int r) {
radius = r;
}
double Circle::getArea(){
return radius * radius * (22.0/7);
}
double Circle:: getCircumference(){
return 2 * radius * (22.0/7);
}
Example creating an object using a pointer variable
Method 1: Creating an object
int main(){
Circle c1,c2(7);
cout<<“The area of c1:”<<c1. getArea()<<“\n”;
//c1.raduis = 5;//syntax error
c1.setRadius(5);
cout<<“The circumference of c1:”<< c1.getCircumference()<<“\n”;
cout<<“The Diameter of c2:”<<c2.getDiameter()<<“\n”;
return 0;
}
Method 2: Pointers
int main( ) {
Circle c(7);
Circle *cp1 = &c;
Circle *cp2 = new Circle (7);
}
Static Variables
• - Shared by all objects of the class
class IntVal {
public:
int getVal();
void setVal(int);
private:
int value;
};
Static Variables
2) Must be defined outside of the class:
class IntVal{
//In-class declaration
};
int IntVal::valCount = 0;
Static Variables
3) Can be accessed or modified by any object of the class: Modifications by one object are visible to all objects
of the class:
class MyCircle{
public:
double r;
};
double MyCircle::pi=3.14;
- this initialisation will only take place once throughout the life of the application
int main(){
- this means that we don’t have to create an instance of the class in order to access static members
Static Variables
• For making a data member static, we require :
(a) Declare it within the class.
(b) Define it outside the class.
• For example
class student
{
Static int count; //declaration within class
-----------------
-----------------
-----------------
};
• The static data member is defined outside the class as :
int student :: count; //definition outside class
• The definition outside the class is a must.
• We can also initialize the static data member at the time of its definition as:
• int student :: count = 0;
Static Member Functions
Static Member Function: A static member function can access only the
static members of a class. We can do so by putting the keyword static before
the name of the function while declaring it for example,
class student
{
static int count;
-----------------
public :
-----------------
-----------------
static void showcount (void) //static member function
{
cout<<”count=”<<count<<”\n”;
}
};
int student ::count=0;
Static Member Functions
• Here we have put the keyword static before the name of the function shwocount ().
• In C++, a static member function differs from the other member functions in the following
ways:
• (i) Only static members (functions or variables) of the same class can be accessed by a
static member function.
• (ii) It is called by using the name of the class rather than an object as given below:
Name_of_the_class :: function_name
For example, student::showcount();
• We use static variables to maintain values common to the entire class for example we can
use a static data member as a counter that records the occurrences of all objects
Static Member Functions
• Can be used to access static member variables
class IntVal{
public:
private:
int value;
};
#include <iostream>
class MyCircle{
public:
double r;
};
double MyCircle::pi=3.14;
int main(){
double p= MyCircle::pi;
double a= MyCircle::area(2);
cout<<"Pi is"<<p<<endl;
cout<<"Area is:"<<a;
return 0; }
Static Member Functions
#include<iostream>
a.getdata(1000);
b.getdata(2000);
c.getdata(3000);
cout<<“After reading data”<<endl;
a.getcount();
b.getcount();
c.getcount();
return 0;
}
Instance members
• Data members and member functions of a class in C++, may be qualified as instance. We
can have instance data members and instance member functions in a class.
Instance data members
• Multiple copies exist in a class as each object has its own copy.
• Changes made by an object will not affect other objects accessing the same instance
variable
Instance functions
• In contrast instance methods can use both static and instance members of a class
class MyCircle{
public:
double r;
static double pi;
static double area(double a){ return a * a* pi; };
double getArea(){ return pi*r*r; }
};
double MyCircle::pi=3.14;
int main(){
double p= MyCicle:: pi;
Arrays as class members
• The array can be used as member variables in a class e.g
const int size=10;
class array{
public:
void setval(void);
void display(void);
};
The array element a[] can be used by member function to perform operations on it
• Consider a shopping list of items for which we place an order with a dealer every month.
The list consists of details such as codenumber and price of each item. We may want to perform
operations such as adding, deleting and print the total value of the order which can be
represented as follows
Arrays as class members
#include <iostream>
using namespace std;
class ITEMS{
int itemCode[m];
float itemPrice[m];
int count;
public:
void getitem(void){
cin>>itemCode[count];
cin>>itemPrice[count];
count++;
}
Arrays as class members
void displaysum(){
float sum=0;
void remove(void) {
int a;
Cin>>a;
if(itemCOde[i]==a)
itemPrice[i]=0;
}
Arrays as class members
void displayItems(){
cout<<“Code Price”;
for(int i=0; i<count; i++){
cout<<itemCode[i]<< “ ” <<itemPrice[i]<<endl;
}
int main(){
ITEMS order;
order.CNT();
int x;
do{
cout<<“You can do the foollowing…..”<<endl;
cout<<“1: Add an item”<<endl;
cout<<“2: Display total value”<<endl;
cout<<“3: Delete an item”<<endl;
cout<<“4: Display all items”<<endl;
cout<<“5: Quit”<<endl;
cout<<“What is your option”<<endl;
cin>>x;
Arrays as class members
switch(x){
case 1: order.getitem(); break;
case 2: order.dispalySum(); break;
case 3: order.remove(); break;
case 4: order.displayItems(); break;
case 5: break;
default: cout<<“Error input try again”<<endl;
}
while(x!=5);
return 0;
}
Objects as Function Arguments
• An object may be used as a function argument in two ways
– A copy of the entire object is passed to the function(pass by value)
• The pass by value method will pass a copy of the object to the function and any changes
made to the object inside the function will not affect the object used to call the function
• The pass by reference method is when an address of the object is passed the called function
works directly on the actual object used in the call. This means that any changes made to the
object inside the function will reflect on the actual object. The passbyreference is more
efficient since it requires to pass only the address of the object and the entire object
Objects as Function Arguments
#include<iostream>
public:
void gettime(int h, int m){
hours= h; minutes=m;
}
void puttime(){
T1.putme();
cout<<“\n T2==”;
T2.putme();
cout<<“\n T3==”;
T3.putme();
return 0;
}
Objects as Function Arguments
• The type and scope of each static member variable must be defined outside the class
definition.
• This is important as static data members are stored separately rather than as part of an
object.
• They are associated with the class itself rather than with any class object hence they are
called class variables. The static variable count is initialized to zero when the objects are
created.
• The count is incremented whenever the data is read into an object. Data is read into objects
three times, the variable count is incremented three times as one copy of count is shared by
all three objects.
• All three output statements cause the value of 3 to be displayed.
•
Constructors
• A constructor (having the same name as that of the class) is a member function which is
automatically used to initialize the objects of the class type with legal initial values.
It has the following properties
• No return type
• Can be overloaded
• Automatically invoked when the object is created. When invoked the signature of the call
must match the constructor definition
• Always declared under the public section
• Cannot be inherited
Syntax of a cconstructor
• It is defined like other member functions of the class, i.e., either inside the class definition or
outside the class definition. For example,
Syntax of a constructor
#include <iostream.h>
using namespace std;
class rectangle {
private :
float length, breadth;
public:
rectangle ()//constructor definition
{
//displayed whenever an object is created
cout<<”I am in the constructor”;
length-10.0;
breadth=20.5;
}
float area()
{
return (length*breadth);
}
};
int main()
{
rectangle rect; //object declared
cout<<”\n The area of the rectangle with default parameters is:”<<rect.area()<<”sq.units\n”;
}
Types of constructor
1. Overloaded constructor
• Besides performing the role of member data initialization, constructors are no different from other functions. This
included overloading also. In fact, it is very common to find overloaded constructors. For example, consider the following
program with overloaded constructors for the figure class :
#include<iostream.>
class figure {
private:
float radius, side1,side2,side3; //data members
public:
figure(float r) { //constructor for circle
radius=r;
}
figure (float s1,float s2) { //constructor for rectangle
side1=s1;
side2=s2;
side3=radius=0.0; //has no significance in rectangle strcpy(shape,”rectangle”);
}
figure (float s1, floats2, float s3) //constructor for triangle
{
side1=s1;
side2=s2;
side3=s3;
radius=0.0;
}
Types of constructor
void area(){ //calculate area
float ar,s;
if(radius==0.0)
{
if (side3==0.0)
ar=side1*side2;
else
ar=3.14*radius*radius;
cout<<”\n\nArea of the “<<shape<<”is :”<<ar<<”sq.units\n”;
}
};
int main() {
figure circle(10.0); //objrct initialized using constructor
figure rectangle(15.0,20.6);//objrct initialized using onstructor
figure Triangle(3.0, 4.0, 5.0); //objrct initialized using constructor
Rectangle.area();
Triangle.area();
return 0;
}
Types of constructor
2 Copy Constructor
• It is of the form classname (classname &) and used for the initialization of an object from
another object of same type. For example,
class fun {
float x,y;
public:
fun (floata,float b){//constructor
x = a;
y = b;
}
fun (fun &f){ //copy constructor
cout<<”\ncopy constructor at work\n”;
x = f.x;
y = f.y;
}
void display (void) {
cout<<””<<y<<end1;
}
};
Here we have two constructors, one copy constructor for copying data value of a fun object to
another and other one a parameterized constructor for assignment of initial values given.
Dynamic Initialisation of objects
In C++, the class objects can be initialized at run time (dynamically). We have the flexibility of
providing initial values at execution time. The following program illustrates this concept:
#include <iostream>
using namespace std;
class employee {
int empl_no;
float salary;
public:
Employee() {} //default constructor
Employee(int empno,float s){//constructor with arguments
Empl_no=empno;
Salary=s;
}
Employee (employee &emp){ //copy constructor
cout<<”\ncopy constructor working\n”;
empl_no=emp.empl_no;
salary=emp.salary;
}
void display (void) {
Cout<<”\nEmp.No:”<<empl_no<<”salary:”<<salary<<end1;
}
};
Dynamic Initialisation of objects
int main()
{
int eno;
float sal;
cout<<”Enter the employee number and salary\n”;
cin>>eno>>sal;
employee obj1(eno,sal);// dynamic initialization of object
For Example,
Here, obj1 will have values of data members num1=0, num2=0 and num3=0
Obj2 will have values of data members num1=5, num2=0 and num3=0
Obj3 will have values of data members num1=10, num2=20 and num3=0
Destructors
Special Characteristics of Destructors
Some of the characteristics associated with destructors are :
(i) These are called automatically when the objects are destroyed.
(ii) Destructor functions follow the usual access rules as other member functions.
(iv) No argument and return type (even void) permitted with destructors.