what is c++ ?
C++ is an object-oriented programming language. It was developed by B.Jarne Strousstrup at AT&T Bell laboratories in Murray Hill, New Jersey, USA, in the early 1980’s. Strousstrup, 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, Strousstrup 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 increment operator ++, thereby suggesting that C++ is an augmented (incremented) version 0f C.Comments: 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. Note that is no closing symbol.
Output Operator: 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 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.
A Look at Procedure – Oriented Programming: Conventional programming, using high level languages such as COBOL, FORTRAN and C, is commonly known as procedure - oriented programming (POP). In the procedure-oriented approach, the problem is viewed as a sequence of things to be done such as reading, calculating and printing. A number of functions are written to accomplish these tasks. The primary focus is on functions.
Some characteristics by procedure-oriented programming are:
Emphasis is on doing 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.
Function transforms data from one form to another.
Employs top-down approach in program design.
Object-Oriented Programming Paradigm:
Some of the striking features of object-oriented programming are:
Emphasis is on data rather than procedure.
Programs are divided into what are known as objects.
Data structures are designed such that they characterize the objects.
Functions that operate on the data of an object are tied together in the data structure.
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.
Follow bottom-up approach in program design.
Organization of data functions in OOP:
Basic Concepts of Object-Oriented Programming:
Objects
Classes
Data Abstractions and encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing
OBJECTS: Objects are the basic run-time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle. They may also represent user-defined data such as vectors, time and lists. Programming problem is analyzed in terms of objects and the nature of communication between them. Program objects should be chosen such that they match closely with the real-world objects. Objects take up space in the memory and have an associated address like a record in Pascal or a structure in C.
Two Ways of representing an object
Classes: The entire set of data and code of an object can be made a user-defined data type with the help of a class. In fact, objects are variables of the data type class. Once a class has been defined, we can create only number of objects belonging to that class. Each object is associated with the data of type class with which they are created. A class is thus a collection of objects of similar type. For example, mango, apple and orange are members of the fruit. Classes are user-defined data types and behave like the built-in types of programming languages. The syntax used to create an object is no different than the syntax used to create an integer object in C. If fruit has been defined as a class, then the statement.
Fruit mango;
Will create an object mango belonging to the class fruit.
Data Abstraction and Encapsulation:
The wrapping up of data and function into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world, and only those functions, which are wrapped in the class, can access it. These functions provide the interface between the object’s data and the program. This insulation of the data from direct access by the program is called data hiding or information hiding.
Abstraction refers to the act of the representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and functions to operate on these attributes. They encapsulate all the essential properties of the objects that are to be created. The functions that operate on these data are sometimes called methods or member function.
Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT).
Inheritance: Inheritance is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchical classification. For example, the bird ‘robin’ is a part of the class ‘flying bird’, which is again a part of the class ‘bird’. The principle 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 features of both the classes.
Property inheritance
Polymorphism: Polymorphism is another important OOP concept. Polymorphism, a Greek term, and means the ability to take more than one form. An operation may exhibit different behaviours 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 were strings, then the operation would produce a third string by concatenation. The process of making an operator to exhibit different behaviours in different instances is known as operator overloading. Using a single function name to perform different types of tasks is known as function overloading.
Polymorphism plays an important role in allowing objects having different internal structure to share the same external interface.
Polymorphism:Dynamic Binding: Binding refers to the linking of a procedural 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 polymorphism and inheritance.
Message Passing: Objects communicate with one another by sending and receiving information much the same way as people pass message to one another.
A message for an object is a request for execution of a procedure, and therefore will invoke a function in the receiving object that generates the desired result. Message passing involves specifying the name of the object, the name of the function and the information to be sent.
Benefits of OOP:
Through inheritance, we can eliminate redundant code and extend the use of existing classes.
The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program.
It is possible to map objects in the problem domain to those in the programs.
It is easy to partition the work in a project based on objects.
Object-oriented systems can be easily upgraded from small to large systems.
Message passing techniques for communication between objects makes the interface descriptions with external systems much simpler.
Software complexity can be easily managed.
Object-Oriented Languages: Languages that support programming with objects are said to be object-based programming languages. They do not support inheritance and dynamic binding. Ada is a typical object-based programming language.
Object-oriented programming incorporates all of object-based programming features along with two additional features, namely, inheritance and dynamic binding. The following statement can therefore characterize object-oriented programming:
Object-based features + inheritance + dynamic binding
Languages that support these features include C++, Smalltalk, Object Pascal and Java. There are a large number of object-based and object-oriented programming languages.
Class: A Class is a collection of objects (or)
A class is a collection of data members & member function (or)
A class is a description of an object.
Specifying a class: A class is a way to bind the data and its associated functions
together. It allows the data (and functions) to be hidden, if necessary, from external use. When defining a class, we are creating a new abstract data type
that can be treated like any other built-in data type. Generally, a class specification has two parts:
1. Class declaration
2. Class function definitions.
The class declartation describes the type and scope of its members. The class function definitions describe how the class functions are implemented.
Class class_name
{
private:
variable declaration;
variable declaration;
public:
variable declaration;
variable declaration;
};
The class body contains the declaration of variables and functions.
These functions and variables are collectively called class members. They are usually grouped uner two sections, namely, private and public to denote which of the members are private and which of them are public. The keywords private and public are known as visibility labels. Note that these keywords are followed by a colon.
The class members that have been declared as private can be accessed only from within the class. On the other hand, public members can be accessed from outside of the class also.
The variables declared inside the class are known as data members and the functions are known as member functions. Only the member functions can have access to the private data members and private functions. However, the public members(both functions and data)can be accessed from outside of the class.
Accessing Class Members : Syntax:
object-name.function-name(actual-arguments);
Ex: x.getadata(100,76.56);
Defining Member Functions:
Member functions can be defined in two places:
1. Outside of the class definition
2. Inside the class definition
Outside of the class definition : An important difference between a member function and a normal function is that a member function incorporates a membership 'identity label' in the header. This 'label' tells the compiler which class the function belongs to. The general form of a member function definition is :
return-type class-name :: function-name(argument declaration)
{
Function body
}
The membership label class-name :: tells the compiler that the function function-name belongs to the class-name. That is, the scope of the function is restricted to the class-name specified in the header line. The symbol :: is called the scope resolution operator.
Inside of the Class : When a function is defined inside a class, it is treated as an inline function. Therefore, all the restrictions and limitations that apply to an inline function are also applicable here. Normally, only small functions are defined inside the class defintions.
Making an Outside function Inline : We can define a member function outside the class definition and still make it inline by just using the qualifier inline in the header line of function definintion.
Nesting of member functions : A member function can be called by using its name inside another member function of the same class. This is known as nesting of member functions.
Private Member Functions : A private member function can only be called by another function that is a member of its class. Even an object cannot invoke a private function using the dot (.) operator.
Memory Allocation for Objects : The member functions are created and placed in the memory space only once when they are defined as a part of a class specification. Since all the objects belonging to that class use the same member functions, no separate space is allocated for member functions when the objects are created. Only space for member variables is allocated separately for each object. Separate memory locations for the objects are essential, because the member variables will hold different data values for different objects.
Static Data Members : It is initialized to zero when the first object of its class is created. No other initialization is permitted.
Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.
It is visible only within the class, but its lifetim is the entire program.
Static variables are normally used to maintain values common to the entire class. For example, a static data member can be used as a counter that records the occurences of all the objects.
Static Member functions : Like static member variable, we can also have static member functions. A member function that is declared static has the following properties : 1. A static function can have access to only other static members (functions or variables) declared in the same class.
2. A static member function can be called using the class name (instead of its objects) as follows :
class-name :: function-name;
Friend Functions: To make an outside function "friendly" to a class, we have to simply declare this function as a friend of the class as shown below:
class SITD
{
private:
...............
...............
public:
...............
...............
friend void cttc(void); //Declaration
};
The function declaration should be preceded by the keyword friend. The function is defined elsewhere in the program like a normal C++ function. The function definition does not use either the keyword friend or the scope operator (::). The functions that are declared with the keyword friend are known as friend functions. A function can be declared as friend in any number of classes. A friend function, although not a member function, has full access rights to the private members of the class.
A friend function possesses certain special characteristics:
1. It is not in the scope of the class to which it has been declared as friend.
2. Since it is not in the scope of the class, it cannot be called using the object of that class.
3. It can be invoked like a normal function without the help of any object.
4. Unlike member functions, it cannot access the member names directly and has to use an object name and dot member ship operator with each member name (E.g.: A.x)
5. It can be declared either in the public or the private part of a class without affecting its meaning.
6. Usually, it has the objects as arguments.
Const Member functions: If a member function does not alter any data in the class, then we may declare it as a const member functions as follows:
void mul (int, int)const;
double get_balance() const;
The qualifier const is appended to the function prototypes (in both declaration). The compiler will generate an error message if such functions try to alter the data values.
Local Classes : Classes can be defined and used inside a function or a block. Such classes are called local classes.
Friend Functions: To make an outside function "friendly" to a class, we have to simply declare this function as a friend of the class as shown below:
class SITD
{
private:
...............
...............
public:
...............
...............
friend void cttc (void); //Declaration
};
The function declaration should be preceded by the keyword friend. The function is defined elsewhere in the program like a normal C++ function. The function definition does not use either the keyword friend or the scope operator (::). The functions that are declared with the keyword friend are known as friend functions. A function can be declared as friend in any number of classes. A friend function, although not a member function, has full access rights to the private members of the class.
A friend function possesses certain special characteristics:
1. It is not in the scope of the class to which it has been declared as friend.
2. Since it is not in the scope of the class, it cannot be called using the object of that class.
3. It can be invoked like a normal function without the help of any object.
4. Unlike member functions, it cannot access the member names directly and has to use an object name and dot member ship operator with each member name (E.g.: A.x)
5. It can be declared either in the public or the private part of a class without affecting its meaning.
6. Usually, it has the objects as arguments.
Constructors: A Constructor is a special function which is invoked whenever an object is created.
The constructor name and the class name should be same. A Constructor cannot return any type of value even void. Constructors cannot be declared is static, const, and virtual.
The constructors can have arguments.
Types of Constructors:
1. Default Constructor: If a constructor with no arguments then the constructor is known as default constructor.
2. Parameter Constructor: If a constructor contains arguments then the constructor is known as parameter constructor.
3. Dynamic Constructor: If a constructor accepts argument values at run time then the constructor is known as dynamic constructor.
4. Default value Parameter Constructor: If a constructor contains default values as arguments then the constructor is known as default value parameter constructor.
5. Copy Constructor: When one object is copied into or assigned into another object then automatically a bit by bit copy is performed. This can be passed by using copy constructor. In the copy constructor a member by member copy is performed.
Destructors: A Destructor is a special function which is invoked whenever an object is destroyed.
Conditions of Destructors:
1. The destructor name and the class name should be same.
2. A class can have contains only one destructor.
3. Destructor can't have any arguments.
4. Destructors can't return any value even void.
5. Destructor must preceded by ~ (Tilde Symbol).
6. Destructors can't be declared is const, static, but destructors are can be virtual.
INHERITANCE: Deriving one class features into another class.
Introduction: Once a class has been written and tested, it can be adapted by other programers to suit their requirements. This is basically done by creating new classes, re-using
the properties of the existing ones. The mechanism of deriving a new class from an old one is called inheritance (or derivation). The old class is referred to as the base class and the new one is called the derived class or subclass.
The derive class inherits some are all of the traits from the base class. A class can also inherit properties from more than one class or from more than one level. A derived class with only one base class, is called single inheritanceand one with several base classes is called multilevel inheritance. On the other hand, the traits of one class may be inherited by more than one class. This process is known as hierarchical inheritance. The mechanism of deriving a class from another 'derived class' is known as multilevel inheritance.
Defining Derived Classes: A derived class can be defined by specifying its relationship with the base class in addition to its own details. The general form of defining a derived class is:
Class derived_classname : visibility_mode base_classname
{
............. //
............. // members of derived class
............. //
}
The colon indicates that the derived-class name is derived from the base-class. The visibility-mode is optional and, if present, may be either private or public. The default visibility-mode is private. Visibility mode specifies whether the features of the base class are privately derived or publicly derived.
When a base class is privately inherited by derived class, 'public members' of the base class become 'private members' of the derived class. When the base class is publicly inherited, 'public members' of the base class become 'public members' of the derived class.
Inheritance: We can also create a new class from already existing class without disturbing the existing class features. This is known as inheritance.
The newly created class is known as subclass or derived class. The existing class is known as super class or base class.
Types of Inheritance:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance.
1. Single Inheritance : When a class is derived from only one base class then the inheritance is known as single inheritance. The base class in the single inheritance is known as direct base class to the derived class.
2. Multilevel Inheritance : When a class is derived from a subclass of another base class then the inheritance is known as multilevel inheritance. The base class is known as indirect base class to the derived class and direct base class to the subclass. The subclass is also known as direct base class to the derived class.
3. Hierarchical Inheritance: When a multiple classes are derived from only one base class then the inheritance is known as hierarchical inheritance.
4. Multiple Inheritance: When a class is derived from more than one base classes then the inheritance is called as multiple inheritance.
5. Hybrid Inheritance: It is a combination of more than one inheritance concepts.
Advantages:
1. Reusability of the code.
2. Here base class functions and members are inherited to derived class. Hence the base class functions and members can be used in the derived class, without rewriting the class.
3. Time is saved is the time involved in designing base class is eliminated since they inherited to derived class.
4. Memory is sav edc which incurred in developing base class members and functions eliminated.
5. Since base class is an existing class and we can retriving base class functions and members into derived class.
Polymrphism : Polymorphism is one of the crucial features of OOP. It simply means 'one name, multiple forms'. We have already seen how the concept of polymorphism is implemented using the overloaded functions and operators. The overloaded member functions are 'selected' for by matching arguments,both type and number. This information is known to the compiler at the compile time and, therefore, compiler is able to select the appropriate function for a particular call at the compile time itself. This is called early binding or Static binding or static linking. Also known as compile time polymorphism, early binding simply means that an object is bound to its function call at compile time.
They are two types of polymorphism.
1. Compile time polymorphism (Early or Static Binding)
a. Function Overloading
b. Operator Overloading
2. Run time polymorphism (Late or Dynamic Binding)
a. Virtual Functiuons
b. Pure Virtual Functions
Virtual Functions: When a function is declared as virtual then the function as virtual function. A function cannot be static functions.
The base class pointer refers the current object address then the function is virtual in the base class.
Pure Virtual Functions: When a function is declared with virtual and initialized with 0 (zero). Then the function is known as pre virtual function.
Syntax of a pure virtual function :-
virtual return_type function_name(arguments) = 0;
Abstract Class : If a class contains one or more pure virtual functions then the class is known as abstract class. We cannot create any objects to the abstract class. Because it is an incomplete (base) class. We should implement the pure virtual function it is the sub class of the parent class.
Introduction : The mechanism of giving such special meanings to an operator is known as operator overloading.
Operator overloading provides a flexible option for the creation of new definitions for most of the C++ operators.
Def : To define an addtional task to an operator, we must specify what it means in relation to the class to which the operator is applied. This is done with the help of a special function, called operator function.
return type classname :: operator op(arglist)
{
Function Body //task defined
}
Operator fuctions must be either member functions(non-static) or friend functions. A basic difference between them is that a friend function will have only one argument for unary operators and two for binary operators,while a member function has no arguments for unary operators and only for binary operators. This is because the object used to invoke the member function is passed implicitly and therfore is available for the member function. This is not the case with friend functions. Arguments may be passed either by value or by reference.
RULES FOR OVERLOADING OPERATORS :
1. Only existing operators can be ooverloaded. New operators cannot be created.
2. The overloaded operator must have at least one operand that is of user-defined type.
3. We cannot change the basic meaning of an operator. That is to say, we cannot redefine the plus(+) operator to subtract one value from the other.
4. Overloaded operators follow the syntax rules of the original operators. They cannot be overridden.
5. There are some operators that cannot be overloaded.
Sizeof -> Size of Operator
. -> Membership Operator
.* -> Pointer-to-Member Operator
:: -> Scope resolution Operator
?: -> Conditional Operator
6. We cannot use friend functions to overload certain operators.
= -> Assignment Operator
() -> Function call Operator
[] -> Subscripting Operator
-> -> Class member access operator
However, member functions can be used to overload them.
7. Unary operators, overloaded by means of amember function, take no explicit arguments and return no explicit values, but, those oveloaded by means of a friend function, take one reference argument. (The object of the relevant Class).
8. Binary operators overloaded through a member function, take one explicit argument and those which are overloaded through a friend function take two explicit arguments.
9. When using binary operators overloaded through a member function, the left hand operand must be an object of the relevant class.
10. Binary arithmetic operators such as +, -, *, and / must explicitly return a value. They must not attempt to change their own arguments.
Function Overloading : The same function name can be used file different
purposes. This is known as function overloading.
Rules of Function Overloading :
1. Function name should be same.
2. The function should contain different number of arguments.
3. A function should contain different types of arguments.
4. Function overloading can't depend on the return type of the function.
Function Overloading or Method Overloading and Function Declaration:
More than one function same name with different types of arguments is called
function overloading.
Here parameters can be differentiate either number of parameters or datatypes
of parameters.
Exception Handling:
Introduction :
The two most common types of bugs are logic errors and syntatic errors. The logic errors occurs due to poor syntatic errors arise due to poor understanding of the language itself. We can detect these errors by using exhaustive debugging and testing procedures.
We often come across some peculiar problems other than logic or syntax errors. They are known as exceptions.
Excption Handling Mechanism :
Basics of Exception Handling :
Excepitions are of two kinds, namely, synchronous exceptions and asynchronous exceptions. Errors such as "out-of-range index" and "over-flow" belong to the synchronous type exceptions. The errors that are caused by events beyond the control of the program (such as keyboard interrupts) ae called asynchronous exceptions. The proposed exception handling mechanism in C++ is designed to handle only synchronous exceptions.
The purpose of the exception handling mechanism is to provide means to detect and report an "exceptional circumstance" so that appropriate action can be taken. The mechanism suggests a separate error handling code that performs the following tasks:
1. Find the problem (Hit the exception).
2. Inform that an error has occured (Throw the exception).
3. Receive the error information (Catch the excepion).
4. Take corrective actions (Handle the exception).
The error hanling code basically consists of two segments, one to detect errors and to throw exceptions and to take appropriate actions.
Exception Handling Mechanism :
C++ exception handling mechanism is basically built upon three keywords, namely, try, throw, and catch. The keyword try is used to preface a block of statements (surrounded by braces) which may generate as try block. When an exception is detected, it is thrown using a throw statement in the keyword catch 'catches' the exception block, and handles it appropriately.
The catch block that catches an exception must immediately folow the try block that throws the exception. The general form of these two blocks are as folows.
Templates : It is a new concept which enable us to define generic classes and functions and thus provides support for generic programming. Generic programming is an approach where generic types are used as parameters in algorthims so that they work for a variety of suitable data types and data structures.
A template can be used to create a family of classes or functions. For example, a class template for an array class would enable us to create arrays of various data types such as int array and float array. Similarly, we can define a template for a function, say mul(), that would help us create various versions of mul() for multiplying int, float and double type values.
A template can be considered as a kind of macro. When an object of a specific type is defined for actual use, the template definition for that class is substituted with the required data type. Since a template is defined with a parameter that would be replaced by a specified data type at the time of the class or function, the templates are sometimes called parameterized classes or functions.
In C++ there are two types of templates.
1. Class template.
2. Function template.
Class Template :
The general format of a class template is:
template
class classname
{
//...............
//class member specification
//with anonymous type T
//wherever appropriate
//...............
};
A class created from a class template is called a template class. The syntax for defining an object of a template class is
classname
This process of creating a specific class from a class template is called instantiation.
Function Template : Like class templates, we can also define function templates that could be used to create a family of functions with different argument types.
template
returntype functionname (arguments of type T)
{
//..........
//Body of function
//with type T
//wherever appropriate
//..........
}
Function template with multiple parameters : Like template classes, we can use more than one generic data type in the template statement, using a comma-separated list as shown below:
template
returntype functionname(arguments of types T1,T2, .....)
{
..........
.......... (Body of function)
..........
}
Example for Templates :
void swap(int a,int b)
{
cout<<"Before swapping the values in a,b are :" <<<", "<<<"\nAfter swapping the values in a,b are :" <<<", "<<<"Before swapping the values in a,b are :" <<<", "<<<"\nAfter swapping the values in a,b are :" <<<", "<<<"Before swapping the values in a,b are :" <<<", "<<<"\nAfter swapping the values in a,b are :" <<<", "<
void swap(T x,T y)
{
T temp;
temp=x;
x=y;
y=temp;
}
The above template generic function swaps integers, floats, characters etc,.
Rules for generic function :-
1. The templates cannot be used inside the main function
2. The generic function template should be written before the main
3. The generic function cannot have prototype (function declaration).
Type Conversion : We know that when constants and variables of different types are mixed in an expression, C applies automatic type conversion to the operands as per certain rules. Similarly, an assignment operation also causes the automatic type conversion. The type of data to the right of an assignment operator is automaticaly converted to the type of the variable on the left. For example, the statements
int A;
float J = 3.4523;
A=J;
convert J to an integer before its value is assigned to A. Thus, the fractional part is truncated. The type conversions are automatic as long as the data types invloved are built-in types.
Files : The I/O system of C++ handles file operations which are very much similar to the console input and output opearations. It uses file streams as an interface between the programs and the files. The stream that supplies data to the program is known as input stream and the one that receives data from the program is known as output stream. In other words, the input stream extracts (or reads) data from the file and the output stream inserts (or writes) data to the file.
(read data) --> I/P stream --> (data I/P)--> program --> (data O/P)--> O/P stream --> (writedata) -->disk files
