What is C++ - E

STUDY MATERIAL
Subject –C++ and Java Programming
Unit – I
Class – II BBA CA
Semester - III
Syllabus: Introduction – Basic concepts of object oriented programming – Beginning with c++
- Tokens, expressions, control structures – functions in c++
Principles of Object-Oriented Programming
Software Evolution
Many programming approaches have been into play from the time of inventions
of the computer. These techniques include modular programming, top-down programming,
bottom-up programming and structured programming. The primary motivation in each case has
been the concern to handle the increasing complexity of programs that are reliable and
maintainable.
To build today’s complex software, it is just enough to put together a sequence of
programming statements and set of procedures and modules but to incorporate sound
construction techniques and program structures that are easy to comprehend, implement and
modify. C, structured programming was a powerful tool that enabled programmers to write
moderately complex programs fairly easily. However, as the programs grew, even the structured
approach failed to show the desired results in terms of bug-free, easy-to-maintain and reusable
programs.
OOP is an approach to program organization and development that
attempts to eliminate some of the pitfalls of conventional programming methods by
incorporating the best of structured features with several powerful new concepts.
Procedure and Object -Oriented Paradigm
Characteristics of Procedure-Oriented Programming.






Emphasis is on during things(algorithms).
Large programs are divided into smaller programs known as functions.
Most of the functions share global data.
Data move openly around the system from function to function.
Functions transform data from one form to another.
Employs top-down approach.
Object-Oriented approach overcomes some of the flaws encountered in the procedural
approach. OOP treats data as a critical element in the program development and it has the
following characteristics as








Emphasis is on data rather than procedure.
Programs are divided into what are known as objects/
Data structures are designed such that they characterize objects.
Functions that operate on the data of an object are tied together in the data
structures.
Data is hidden and cannot be accessed by external functions.
Objects may communicate with each other through functions.
New data and functions can be easily added whenever necessary.
Follows bottom-up approach.
Object Oriented Programming:
Object oriented programming is a kind of innovation in programming languages and its
important because it depicts the real world situation in a much simpler form. It is more reliable,
less confusion and less complexities. C++ is one such object oriented programming language.
Object Oriented programming has a lot of new concepts like.
 Any real world situation can be clubbed as objects
 Class is a collection of objects which is of similar type
 Object is just combining the data and the functions that operate on that data. It is
an instance of a particular class.
Encapsulation - The Wrapping up of data and functions into a single unit (called
class) is known as encapsulation.
Data Hiding - The data is not accessible to the outside world and only those
functions which are wrapped in the class can access it. This insulation of data from direct
access by the program is called data hiding.
Polymorphism – The ability to take more than form is known as polymorphism.
Inheritance - Inheritance is the process by which objects of one class acquire the
properties of objects of another class. It provides the concept of reusability.
Benefits Of OOPS:
This new technology promises greater productivity, better quality software and lesser
maintenance cost. Other advantages are
 Existing classes can be extended using inheritance that avoids redundant code.
 Data hiding helps the programmer to build secure programs and so it cannot be
invaded by code in other parts of the program.
 Multiple instances of an object can co-exist with out any interference.
 It is easy to partition work in a project based on objects
 Object oriented systems can be easily upgraded from small to large systems
 Communication between objects is simpler.
 Software complexities are easily manageable.
 Few features to be incorporated in Object oriented systems are:
OBJECT-ORIENTED LANGUAGES:
Object oriented programming languages are classified into two types based on the
concepts they support. The two types are
 Object-based languages
 Object-oriented languages
Object-based languages is that style of programming that supports encapsulation and
object identity. The other features available in this type are Data hiding, Automatic initialization
and clear up of objects, operator overloading. It also supports programming with objects. The
two features that are not supported by object-based languages are dynamic binding and
inheritance. E.g. Ada
Object-oriented languages incorporates in it features like data hiding, encapsulation,
operator overloading, automatic initialization and clear-up of objects, along with inheritance and
dynamic binding. E.g. C++, Object Pascal, Small Talk
In general,
Object-oriented language=Object-based + inheritance + Dynamic binding
Applications Of Object-Oriented Programming:
The most popular applications of object-oriented programming has been in the area of
user interface design such as windows. Promising areas for application of oops includes:








Real-time systems
Simulating and modeling
Object-oriented databases
Hypertext, Hypermedia and expert text
Artificial Intelligence and expert systems
Neural networks and parallel programming
Decision support and office automation systems
Computer Integrated Manufacture/Computer Aided Design and Manufacture etc
Object-oriented paradigm came from a language, matured into design and has
now moved into analysis. This technology is going to change the way software engineers think,
analyze, design and implement systems in future.
Beginning with C++
What is C++
C++ is an object-oriented programming language. Initially named with ‘C with Classes’, C++
was developed by Bjarne Stroustrup at AT&T Bell laboratories in Murray Hill, New Jersey,
United States of America , in the early eighties. Stroustrup, an admirer of Simula67 and a strong
supporter of C, wanted to combine the best of both languages and create a powerful language
that could support object-oriented programming features and still retain the power and elegance
of C. This result was C++.
C++ is a superset of C. The three most important facilities that C++ adds on to C are classes,
function overloading, and operator overloading. The addition of new features has transformed C
from a language that currently facilitates top-down, structured design, to one that provides
bottom-up, object-oriented design.
Applications of C++
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 application systems.
Since C++ allows us to create hierarchy-related objects, special object-oriented libraries
can be build that can be used later by many programmers. C++ programs are easily maintainable
and expandable.
C++ Statements
C++ is a collection of functions. Execution begins at main(). Every C++ program must
have a main(). C++ is a free-form language. Like C, C++ terminates with semicolon.
C++ introduces a new comment symbol //(double slash). Comments 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. There is no closing symbol.
For e.g.
//This is an example of
//C++ program to illustrate
//some of its features.
The C comment symbols /*, */ are still valid and more suitable for multilane comments.
For e.g.
/*This is an example of
C++ program to illustrate
some of its features.*/
Output Operator
C++ introduces two new C++ features, cout and <<. The identifier cout is a predefined
object that represents the standard output stream in C++. The standard output stream represents
the screen.
The operator << is called the insertion or put to operator. It inserts(or sends) the contents
of the variable on its right to the object on its left.
For e.g.
cout << “C++ is better C.””;
cout << string;
Input Operator
The identifier cin is a predefined object that represents the standard input stream
in C++. The standard input stream represents the keyboard.
The operator >> is called the extraction or get from operator. It extracts(or takes) the
value from the keyboard and assigns it to variable on the its right.
For e.g.
cin >> string;
Structure Of C++ Program
A typical C++ program would contain four sections as shown in the diagram. These
sections may be placed in separate code files and then compiled independently or jointly.
Structure of a C++ Program
It is a common practice to organize a program into three separate files. The class
declarations are placed in a header file and the definitions of member functions go into another
file. This approach enables the programmer to separate the abstract specification of the interface
(class definition) from the implementation details (member functions definition). Finally, the
main-program that uses the class is placed in a third file which "includes" the previous two files
as well as any other files required.
This approach is based on the concept of client-server model. The class definitions
including the member functions constitute the server that provides services to the main program
known as client. The client uses the server through the public interface of the class.
Tokens, Expressions and Control Structures
Tokens
The smallest individual units in a program are known as tokens. C++ has the following
tokens:
 Keywords
 Identifiers
 Constants
 Strings
 Operators.
A C++ program is written using these tokens, white spaces, and the syntax of the
language.
Keywords
They are explicitly reserved identifiers and cannot be used as program variables or other
user-defined program elements.
C++ Keywords
char
int
if
then
Identifiers
Identifiers refer to the names of variables, functions, arrays, classes etc. created by the
programmer. Each language has its own rules for naming these identifiers. They are both
common to both C and C++:
 Only alphabetic characters,digits and underscores are permitted.
 The name cannot start with a digit.
 Uppercase and lowercase letters are distinct.
 A declared keywoird cannot be used as a variable name.
A major difference between C and C++ is the limit on the length of a name. While ANSI C
recognizes only the first 32 characters in a name, C++ has no limit the length of a name.
Basic Data Types
Both C and C++ compilers support all the built in data types. With the exception of void,
the basic data types may have several modifiers preceding then to the serve the needs of various
situations. The modifiers signed, unsigned , long, and short may be applied to character and
integer basic data types.
Two normal uses of void are
1) to specify the return type of a function when it is not returning any value
2) to indicate an empty argument list to a function.
E.g. void fn1(void)
Size and range of C++ basic data types
Hierarchy of C++ data types
User-Defined Data Types
Structures and Classes
Data types such as struct and union in C are also valid in C++. C++ also permits us to
define another user-defined data type known as class. The class variables are known as objects,
which are the central focus of object –oriented programming.
Enumerated Data type
An enumerated data type is another user-defined type which provides a way for attaching
names to number , thereby increasing comprehensibility of the code. The enum keyword
automatically enumerates a list of words by assigning then values(0,1,2,..).
For e.g.
enum color(red,blue,green);
color background; // background is of type color
Control Structures
One method of achieving the objective of an accurate, error –resistant and maintainable
code is to use one or any combinations of the following three control structures:
1. Sequence structure (Straight line)
2. Selection structure ( branching)
3. Loop structure (Iteration or repetition).
These structures are implemented using one-entry, one-exit concept .
The if statement
The if statement is implemented in two forms:
1) Simple statement
if (conditional exp)
{
action1;
}
action2;
action3;
2) if..else statement.
if (conditional expression)
{
action1;
}
else
{
action2;
}
action3;
The switch Statement
This is a multiple-branching statement where, based on a condition, the control is transferred to
one of the many possible points. This is implemented as follows:
switch (expression)
{
casel:
{
action 1;
}
case2:
{
action2:
}
case3:
{
actions:
}
default:
{
action4;
}
}
action 5;
The do-while Statement
The do-while is an exit-controlled loop. Based on a condition, the control is transferred back to
a particular point in the program. The syntax is as follows:
do
{
action 1;
}
while(condition is true);
action2;
The while Statement
This is also a loop structure, but is an entry-controlled one. The syntax is as follows:
While (condition is true)
{
action 1;
}
action 2;
The for Statement
The for is an entry-entrolled loop and is used when an action is to be repeated for a
predetermined number of times. The syntax is as follows:
for (intial value;test;increment)
{
action1;
}
action2;
Operator Precedence
C++ enables multiple meanings to the meanings to the operators, their association and
precedence remains the same. For example, the multiplication operator will continue having
higher precedence than the add operator. The precedence and associativity of all the C++
operators are listed below in the order of decreasing precedence.
Operator
Associativity
::
- . ( ) [] postfix++ postfix-prefix++ prefix-- ~ ! unary + unary –
unary * unary & (type) sizeof new delete
- * *
* / %
+<< >>
< <= > >=
== !=
left to right
left to right
right to left
left to right
left to right
left to right
left to right
left to right
left to right
&
^
|
&&
||
?:
= *= /= %= += -=
<<= >>= &= ^= |=
left to right
left to right
left to right
left to right
left to right
left to right
right to left
FUNCTION IN C++
Introduction
Functions play an important role in programming. Dividing a program into function is
one of the major principles of top-down, structured programming. Another advantage is
reducing the size of the programs. As a result, functions remain as the building blocks of
C++ programs with some additional features.
The Main function
In ANSI C,
The definition of main( )
Main( )
{
//main program statements
}
The starting point for the execution of a program is main ( ) that does not return any value. In
C++, main() returns a value of type int to the operating system. Therefore, C++ explicity
defines main( ) as
int main( )
{
……
……
return(0);
}
The functions that have a return value should use the return statement for termination.
Function Prototyping
The prototype describes the function interface to the compiler by giving details such
as the number and type of arguments and the type of return values. When a function is
called, the compiler ensures that proper arguments are passed or the return value is correct.
Any violation in matching the arguments or the return types will be indicated by the compiler
at the time of compilation itself. In C++, function prototyping is essential.
Function prototyping is a declaration statement in the calling program and with the
syntax as follows:
type function-name(argument-list);
The argument list contains the types and names of arguments that must be passed to the
function. Each argument variable must be declared independently inside the parentheses. The
variable names in the argument list can be excluded.
For e.g.
float mean(int a, int b)
Inline functions
The concepts in using functions in programs is to save memory space, which becomes
appreciable when a function is called many times. Every time a function is called, it takes a
lot of extra time in executing a series of instructions for tasks such as jumping to the
function, saving registers, pushing registers, pushing arguments into the stack and returning
to the calling function. When a function is small, a substantial percentage of execution time
is spent in such overheads.
In C++, solution to above problem is the use of inline functions. An inline function is a
function that is expanded in line when it is invoked. The compiler replaces the function call
with the corresponding function code, Definition of inline functions is
inline function-header
{
function body
}
Example
inline double cube(double a)
{
return(a*a*a);
}
Inline function is invoked by statement like
c = cube(2.0);
All inline functions must be defined before they are used. The speed benefits of inline
functions are lost as the size of inline function grows. In such cases, the use of normal
function will be more meaningful. As a result, the function are made inline when they are
small enough to be defined in one or two lines.
The keyword inline indicates a request to the compiler and this request is ignored if the
function is too long or complicated. The other situations when inline functions do not work
are
 If the function has a loop, switch or goto statements
 If the function contains static variables
 If the function is recursive
 If the return statement does not exist
Inline function is advantageous in the fact that the program runs faster but it
consumes memory because the function is inserted at each point the function is called.
Friend Functions
A non-member function cannot have access to the private data of a class, if there arises a
situation where two classes have to share a particular function, then the concept of friends is
used. A common function can be made a friend to both the classes thereby allowing its
access to the private data members. The syntax to declare a non member function is:
class abc
{
------public:
----friend void xyz();
//friend function declaration
};
A function can be a friend of a number of classes. As a result, a non-member function has
the rights to access the private members of a class. A few of its characteristics are :
 It is not within the scope of the class.
 It cannot be called using the object of the class, but it is invoked like a normal
function.
 It cannot access the member data directly and it has to use the dot operator
and object .name to do so.
 Generally, objects are its arguments.
 Member functions of one class can be a friend function of another class.
The following example shows one member function of one class as a friend of
another class.
For eg.,
Class x
{
--public:
int fun1(); //member function
--};
class y
{
--public:
friend int x::fun1();
//fun1() of class x is a friend of class y.
};
All the member functions of one class can be declared as a friend of another class.
For e.g.
Class two
{
friend class one;
};