C++ PROGRAMMING
MAYANK SINGH (CODE_WITH_MAYANK)
What is C++?
Why Use C++ ?�
#include<iostream.h>
#include <iostream.h> is a header file library that lets us work with input and output objects, such as cout , cin. Header files add functionality to C++ programs. �
Cout Function
is used to output values/print text:
Cin Function
from the keyboard with the extraction operator
(>>).
Program to print msg. ?
#include<iostream.h>
#include<conio.h>
Void main()
{
Cout<<“hello world….!”;
Getch();
}
OOPS
Characteristics of an OOPS
CLASS
OBJECT
ENCAPSULATION
ABSTRACTION
POLYMORPHISM
INHERITANCE
ACCESS SPECIFIERS (ACCESS MODIFIERS)
In C++, there are three access specifiers:
EXAMAPLE OF CLASS AND OBJECT
#Include<iostream.h>
#include<conio.h>
Class Abhi{ //defining class
Private: // access specifier
Int a,b; // data members
};
Int main()
{
Abhi a1; //creating object as a1
a1.a=12; // assigning values in data members
a1.b=13;
Cout<<“sum of members=”<<a1.a+a1.b;
}
Sum of members=25
Example of Public and Private Access specifier
class MyClass {�public: // Public access specifier�int x; // Public attribute�private: // Private access specifier�int y; // Private attribute�};
int main() {� MyClass myObj;� myObj.x = 25;//Allowed� myObj.y = 50;//Not allowed� return 0;�}
By default, all members of a class are PRIVATE if you don't specify an access specifier:
Class with Methods
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
Note: You access methods just like you access attributes; by creating an object of the
class and using the dot syntax (.)
Inside class definition
class MyClass { // The class� public: // Access specifier
// Method/function defined inside the class� void myMethod() { � cout << "Hello World!";� }�};��
int main() {� // Create an object of MyClass
MyClass myObj;
// Call the method� myObj.myMethod(); � return 0;�}
Outside class definition
class MyClass { // The class� public: // Access specifier
// Method/function declaration� void myMethod(); �};�// Method/function definition outside the class�void MyClass::myMethod() {� cout << "Hello World!";�}�
int main() {
// Create an object of MyClass� MyClass myObj;
// Call the method� myObj.myMethod(); � return 0;�}
EXAMPLE OF PRIVATE WITH METHODS
class test{
private:
int a,b;
public:
void display(){
cout<<"sum of a+b="<<a+b;
}
void setdata(int c,int d){
a=c;
b=d;
}
};
int main()
{
test aa;
aa.setdata(12,13);
aa.display();
return 0;
}
C++ Constructor
CONSTRUCTOR is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure.
There can be two types of constructors in C++.
Default Constructor
A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.
#include <iostream>
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked";
}
};
int main()
{
Employee e1; //creating an object Employee e2;
return 0;
}
Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct objects.
#include<iostream.h>
class demo{
int a,b;
public:
demo(int ac,int bc)
{
a=ac;
b=bc;
}
void show(){
cout<<"sum="<<a+b;
}
};
void main(){
demo a(12,13);
a.show();
}
Copy Constructor�A Copy constructor is an overloaded constructor used to declare and initialize an object from another object.
Copy Constructor is of two types:
The programmer defines the user-defined constructor.
Syntax Of User-defined Copy Constructor:
class A
{
A(A &x) // copy constructor.
{
// copyconstructor.
}
}
When Copy Constructor is called
Copy Constructor is called in the following scenarios:�1)When we initialize the object with another existing object of the same class type. For example, Student s1 = s2, where Student is the class.�2)When the object of the same class type is passed by value as an argument.�3)When the function returns the object of the same class type by value.
Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only once in a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is prefixed with a tilde sign (~).
Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.
Friend function
Declaration of friend function
Enumeration
Enum in C++ is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The C++ enum constants are static and final implicitly.
C++ Enums can be thought of as classes that have fixed set of constants.
Points to remember for C++ Enum
THIS Pointer (Keyword)
In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++.
Inheritance
Inheritance is a process in which one object acquires all the properties and behaviors of its parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviors which are defined in other class.
In c++, the class which inherits the members of another class is called derived class and the class whose members are inherited is called base class. The derived class is the specialized class for the base class.
Advantage of C++ Inheritance
Code reusability: Now you can reuse the members of your parent class. So, there is no need to define the member again. So less code is required in the class.
Types Of Inheritance
five types of inheritance:
Derived Class
A Derived class is defined as the class derived from the base class.
The Syntax of Derived class:
class derived_class_name : visibility-mode base_class_name
{
// body of the derived class.
}
derived_class_name: It is the name of the derived class.
visibility mode: The visibility mode specifies whether the features of the base class are publicly inherited or privately inherited. It can be public or private.
base_class_name: It is the name of the base class.
Note:
Single Inheritance�Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base class.
A
B
Base
Class
Derived
Class
Class A gives properties to Class B
METHODS INHERIT
Multilevel Inheritance�
When one class inherits another class which is further inherited by another class, it is known as multi level inheritance in C++. Inheritance is transitive so the last derived class acquires all the members of all its base classes.
A
C
B
Multiple Inheritance�Multiple inheritance is the process of deriving a new class that inherits the attributes from two or more classes.��
A
B
C
D
Syntax of the Derived class
class D : visibility B-1, visibility B-2, ?
{
// Body of the class;
}
Hybrid Inheritance�Hybrid inheritance is a combination of more than one type of inheritance.
A
B
C
D
MULTILEVEL INHERITANCE
MULTIPLE INHERITANCE
Hierarchical Inheritance�Hierarchical inheritance is defined as the process of deriving more than one class from a base class.
C
A
D
B
A is a base class
B,C,D is a derived class
Polymorphism�The term "Polymorphism" is the combination of "poly“ +"morphs" which means many forms. It is a Greek word.
Real Life Example Of Polymorphism
A lady behaves like a teacher in a classroom, mother or daughter in a home and customer in a market. Here, a single person is behaving differently according to the situations.
There are two types of polymorphism:
Compile time polymorphism:
The overloaded functions are invoked by matching the type and number of arguments. This information is available at the compile time and, therefore, compiler selects the appropriate function at the compile time. It is achieved by function overloading and operator overloading which is also known as static binding or early binding. Now, let's consider the case where function name and prototype is same.
STATIC BINDING
Overloading (Function and Operator)
If we create two or more members having the same name but different in number or type of parameter, it is known as C++ overloading. In C++, we can overload:
Types of overloading in C++:
Function Overloading
Function Overloading is defined as the process of having two or more function with the same name, but different in parameters is known as function overloading in C++. In function overloading, the function is redefined by using either different types of arguments or a different number of arguments. It is only through these differences compiler can differentiate between the functions.
Operators Overloading
Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type. For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the built-in data types.
The advantage of Operators overloading is to perform different operations on the same operand.
Operator that cannot be overloaded are as follows:
Syntax of Operator Overloading(outside class)
return_type class_name : : operator op(argument_list)
{
// body of the function.
}
Rules for Operator Overloading
OPERATOR
INCREMENT OPERATOR OVERLOADING
Binary operator overloading�Rule(left = calling)(right =argument)
RUN TIME POLYMORPHISM
DYNAMIC BINDING
Function Overriding
If derived class defines same function as defined in its base class, it is known as function overriding in C++. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of the function which is already provided by its base class.
Single Inheritance overridding
Multiple Inheritance overridding
virtual function
A virtual function is a member function which is declared within a base class and is re-defined(Overriden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.
In late binding function call is resolved during runtime. Therefore compiler determines the type of object at runtime, and then binds the function call.
Late binding or Dynamic linkage
Rules of Virtual Function
Pure Virtual Function
Interfaces in C++ (Abstract Classes)
Abstract classes are the way to achieve abstraction in C++. Abstraction in C++ is the process to hide the internal details and showing functionality only. Abstraction can be achieved by two ways:
Abstract class and interface both can have abstract methods which are necessary for abstraction.
C++ Abstract class�In C++ class is made abstract by declaring at least one of its functions as <>strong>pure virtual function. A pure virtual function is specified by placing "= 0" in its declaration. Its implementation must be provided by derived classes.
Data Abstraction in C++
Data Abstraction can be achieved in two ways:�Abstraction using classes�Abstraction in header files.
Abstraction using classes: An abstraction can be achieved using classes. A class is used to group all the data members and member functions into a single unit by using the access specifiers. A class has the responsibility to determine which data member is to be visible outside and which is not.
Abstraction in header files: An another type of abstraction is header file. For example, pow() function available is used to calculate the power of a number without actually knowing which algorithm function uses to calculate the power. Thus, we can say that header files hides all the implementation details from the user.
Abstraction in header files:
Abstraction using classes:
C++ Strings
In C++, string is an object of string class that represents sequence of characters. We can perform many operations on strings such as concatenation, comparison, conversion etc.
�String Compare
Example of string comparison using strcmp() function.
C++ string class
�String Concat
Example of string concatenation using strcat() function.
String Copy
Example of copy the string using strcpy() function.
String Length
Example of finding the string length using strlen() function.
C++ Recursion
When function is called within the same function, it is known as recursion in C++. The function which calls the same function, is known as recursive function.
A function that calls itself, and doesn't perform any task after function call, is known as tail recursion. In tail recursion, we generally call the same function with return statement.
recursionfunction(){
recursionfunction(); //calling self function
}
C++ Files
The fstream library allows us to work with files.
To use the fstream library, include both the standard <iostream> AND the <fstream> header file:
Create and Write To a File
To create a file, use either the ofstream or fstream class, and specify the name of the file.
To write to the file, use the insertion operator (<<).
Read a File
To read from a file, use either the ifstream or fstream class, and the name of the file.
Note that we also use a while loop together with the getline() function (which belongs to the ifstream class) to read the file line by line, and to print the content of the file:
Read and write files
FSTREAM FILE HANDLING(WRITE MODE)
FSTREAM FILE HANDLING(APPEND MODE)
FSTREAM FILE HANDLING(READ MODE)
C++ Templates
A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types.
Templates can be represented in two ways:
Function Templates:
We can define a template for a function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values.
Class Template:
We can define a template for a class. For example, a class template can be created for the array class that can accept the array of various types such as int array, float array or double array.
Function Template
Syntax of Function Template
template < class Ttype>
ret_type func_name(parameter_list) {
// body of function.
}
Function TEMPLATE
CLASS TEMPLATE
A class template must be declared before any instantiation of a corresponding template class. A class template definition can only appear once in any single translation unit. A class template must be defined before any use of a template class that requires the size of the class or refers to members of the class.
C++ Exceptions Handling
When executing C++ code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message. The technical term for this is: C++ will throw an exception (throw an error).
C++ try and catch
Exception handling in C++ consist of three keywords: try, throw and catch:
SYNTAX
try {� // Block of code to try� throw exception; // Throw an exception when a problem arise�}�catch (type Arg) {� // Block of code to handle errors�}
Handle Any Type of Exceptions (...)�If you do not know the throw type used in the try block, you can use the "three dots" syntax (...) inside the catch block, which will handle any type of exception:�
DATA STRUCTURE
AND ALGORITHMS
Why to Learn Data Structure and Algorithms?
As applications are getting complex and data rich, there are three common problems that applications face now-a-days.
Algorithms Basics
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output. Algorithms are generally created independent of underlying languages, i.e. an algorithm can be implemented in more than one programming language.
From the data structure point of view, following are some important categories of algorithms −
Characteristics of an Algorithm
Not all procedures can be called an algorithm. An algorithm should have the following characteristics −
How to Write an Algorithm?
There are no well-defined standards for writing algorithms. Rather, it is problem and resource dependent. Algorithms are never written to support a particular programming code.
�As we know that all programming languages share basic code constructs like loops (do, for, while), flow-control (if-else), etc. These common constructs can be used to write an algorithm.
�We write algorithms in a step-by-step manner, but it is not always the case. Algorithm writing is a process and is executed after the problem domain is well-defined. That is, we should know the problem domain, for which we are designing a solution�
Making Algorithm
PROBLEM − Design an algorithm to add two numbers and display the result.
Step 1 − START
Step 2 − declare three integers a, b & c
Step 3 − define values of a & b
Step 4 − add values of a & b
Step 5 − store output of step 4 to c
Step 6 − print c
Step 7 − STOP
Writing step numbers, is optional.�We design an algorithm to get a solution of a given problem. A problem can be solved in more than one ways.
Algorithm Analysis
Algorithm Complexity
Suppose X is an algorithm and n is the size of input data, the time and space used by the algorithm X are the two main factors, which decide the efficiency of X.
The complexity of an algorithm f(n) gives the running time and/or the storage space required by the algorithm in terms of n as the size of input data
Data Definition
Data Definition defines a particular data with the following characteristics.
Data Object
Data Object represents an object having a data.
Data Type
Built-in Data Type
Those data types for which a language has built-in support are known as Built-in Data types. For example, most of the languages provide the following built-in data types.
Derived Data Type
Those data types which are implementation independent as they can be implemented in one or the other way are known as derived data types. These data types are normally built by the combination of primary or built-in data types and associated operations on them. For example −
Basic Operations
The data in the data structures are processed by certain operations. The particular data structure chosen largely depends on the frequency of the operation that needs to be performed on the data structure.
Array Representation
Arrays can be declared in various ways in different languages. For illustration, let's take C array declaration.
Basic Operations
Following are the basic operations supported by an array.
TRAVERSE
INSERTION
DELETION
SEARCHING
UPDATION
Dynamic Memory(using NEW KEYWORD)