C++ Full Notes
C++ Full Notes
C++ Full Notes
HISTORY OF C++
• According to IEEE C++ Language is the 4th most
popular language .
• The C++ programming language has a history going
back to 1979, when Bjarne Stroustrup (FATHER of
C++ ).
• He is currently working on the UNIX kernel for
distributed system for his Ph.D. thesis
Reason to develop C++….
• Stroustrup found that Simula65( 1979 popular lang.) had
features (Oop’s) that were very helpful for large software
development, but the language was too slow for practical use,
while BCPL was fast but too low-level to be suitable for large
software development.
• When Stroustrup started working in AT&T Bell Labs, he had
the problem of analyzing the UNIX kernel with respect
to distributed computing.
• Remembering his PhD experience, Stroustrup set out to
enhance the C language with Simula-like features.
• C was chosen because it was general-purpose, fast, portable
and widely used.
• In 1982 e builds a new language known as “C with Classes”
here C language is implemented along with the new concept
of OBJECT ORIENTED CONCEPT(Oop’s).
• Later in 1983 it is renamed as C++ where (++) symbol is a
(increment operator) which shows it is a INCREMENT in the
features of the basic C Language.
• In 1998 the C++ first official version known as (C++98) is
published in the market.
• C++ is standardized by the International Organization for
Standardization (ISO), with the latest standard version ratified
and published by ISO in December 2020 as ISO/IEC
14882:2020 (informally known as C++20).
BASICS OF C++
• C++ is middle level language.
• Compiler turbo c++.
• File extension (.cpp).
• Follow the concept of Oop's.
• Used for development of OS, System Drivers,
Browsers, Games etc.
• Ex : Adobe Photoshop, Amazon site.
Definition of c++
• C++ is a statically typed, compiled, general-purpose,
case-sensitive, free-form programming language that
supports procedural, object-oriented, and generic
programming.
• C++ is regarded as a middle-level language, as it
comprises a combination of both high-level and low-level
language features.
• C++ was developed by Bjarne Stroustrup starting in 1979
at Bell Labs in Murray Hill, New Jersey, as an
enhancement to the C language and originally named “C
with Classes” but later it was renamed “C++” .
Features of C++
1. SIMPLE:- C++ is one of the most-simple languages when it comes to
programming. It is also easy to understand and learn as it originated
from the C programming language.
2. Object Oriented Programming:- One of the most important features
because of which C++ got famous. Everything is treated as objects in
C++ that’s why it is called object-oriented programming. Objects are
used for performing all kinds of functionalities. It has
various features like Polymorphism and Inheritance.
3. PORTABILITY:- C++ is not platform independent but we can say it is
portable enough to run on different machines by adding some or no
changes at all.
4. Mid-Level Programming Language:- C++ programming language is a
collection of special features of low-level languages and high-level
languages.
5. Rich Library:- C++ library is full of in-built functions that save a huge
amount of time in the software development process.
6. Case Sensitive:- As C++ is originated from C, it is also purely
CASE sensitive that means lowercase and uppercase characters
written in code will have completely different meaning and will be
treated differently.
7. Compiler-Based:- Means Without compilation, you can’t execute
any C++ code.
8. Dynamic Memory Allocation:- Due to pointer support in the C++
language. Memory allocation can be easily done dynamically rather
than static.
9. Recursion:- Due to code reusability features, we can call any function
within a function saving memory space by not writing the same code
again and again. Code reusability is there for every function.
10. Fast:- As compared to other programming languages. Execution time
and Compilation time of a code written in C++ language are faster
than any other programming language.
Uses/Applications of C++
Language
1. Operating Systems: Be it Microsoft Windows, APPLE(Mac OS-X),
Linux and SYMBIAN OS (One of the most widespread OS’s for
cellular phones) – all of them are programmed in C++.
2. Browsers: The rendering engines of various web browsers are
programmed in C++ simply because if the speed that it offers. Eg
MOZILLA FIREFOX
3. Libraries: Many high-level libraries use C++ as the core
programming language. For instance, several Machine Learning
libraries use C++ in the backend because of its speed. Tensorflow,
one of the most widely used Machine Learning .
4. Graphics: All graphics applications require fast rendering and just
like the case of web browsers, here also C++ helps in reducing the
latency. Eg Maya3D modelling and animation software.
5. Banking Applications: One of the most popularly used core-banking
system – Infosys uses C++ as one of the backend programming languages
and BLOOMBEG( SW provide real time financial information to investors)
6. Cloud/Distributed Systems: Large organizations that develop cloud
storage systems and other distributed systems also use C++ because it
connects very well with the hardware and is compatible with a lot of
machines.
7. Databases: MySQL – the most widely used databases are written in C++
and C.
8. Compilers: The compilers of various programming languages use C and
C++ as the backend programming language. This is because of the fact
that both C and C++ are relatively lower level languages and are closer to
the hardware and therefore are the ideal choice for such compilation
systems.
OBJECT ORIENTED
METHODOLOGY USING C++
SOFTWARE EVOLUTION
• During the time of COMPUTER evolution there are
many different programming techniques are used,
1. Machine language (uses 0 and 1).
2. Assembly language (used in microprocessor).
3. Procedure Oriented language eg: COBOL, FORTRAN,
C language (used in compiler designing).
4. Object–Oriented Programming language eg: C++
language(partial), Java, c# etc...
Procedure-Oriented Programming(POP)
1. Documentation Section
• comments.(// or /*………..*/)
• Preprocessor Directives
• Global Declaration Section
• Class declaration or definition
• Data members declare.
• Member function declare and define.
• Main Function declaration.
• Object declaration part.
• Accessing member functions (using dot operator).
Documentation Section
• In Documentation section we give the Heading and
Comments. Comment statement is the non-executable
statement. Comment can be given in two ways:
• The general syntax is: #include <header file> .or #include "header file"
For example: #include <iostream.h>, #include <conio.h> , #include "dos.h“
•Definition Section: The second section is the Definition section by using which we
can define a variable with its value. For this purpose define statement is used.
• The general syntax is: #define variable name value
For example:
•#define PI 3.142
•#define A 100
•#define NAME "Dinesh"
Global Declaration Section
• Data Members
• These are the data-type properties that describe the characteristics of a class. We
can declare any number of data members of any type in a class. We can say that
the variables in C and data members in C++.
• example: float area; int a=10
• Member Functions
• These are the various operations that can be performed to data members of that
class. We can declare any number of member functions of any type in a class.
Member functions are access using object and dot operator.
• example: void read(), void display()
4. Access Specifier
• Access Specifier are used to identify access rights for the data
members and member functions of the class. Depending upon the
access level of a class member, access to it is allowed or denied.
• There are three main types of access Specifier in C++ programming
language:
1. Private: A private member within a class denotes that only
members of the same class have accessibility. The private member
is not accessible from outside the class boundary.
2. Public: Public members are accessible from outside the class
boundary.
3.Protected: A protected access specifier is a stage between private
and public access. If member functions defined in a class are
protected, they cannot be accessed from outside the class but can
be accessed from the derived class (inheritance).
Main Function()
1. Object declaration part
• We can declare objects of class inside the main program or outside the
main program.
• Defining objects of class data type is known as class instantiation
(instances of class).
• example: Circle c1 (c1 is the object of the class Circle).
}
};
Int main ( ) Main program starts
{
clrscr();
Display d1; Object of the class is created
d1.detdata( ); Member functions is accessed through object.
d1.showdata( );
getch( );
return 0;
}
OPERATORS IN C++
Scope resolution operator in C++
• Scope resolution operator is used to get the hidden names due to
variable scopes so that you can still use them.
• In C++, scope resolution operator is (::) It is used for following purposes.
int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x; //output 30
cout << "\nValue of local x is " << x; //output 10
return 0;
}
2) To define a function outside a class.
#include<iostream>
class A
{
public:
int main()
{ A a;
a.fun();
return 0;
}
Memory allocated/de allocated in
C++?
• C uses malloc() and calloc() function to allocate memory dynamically at
run time and uses free() function to free dynamically allocated memory.
C++ supports these functions and also has two
operators new and delete that perform the task of allocating and freeing
the memory in a better and easier way.
new operator
• The new operator denotes a request for memory allocation on the Heap. If
sufficient memory is available, new operator initializes the memory and
returns the address of the newly allocated and initialized memory to the
pointer variable.
• Syntax to use new operator: To allocate memory of any data type, the
syntax is:
• Pointer_variable = new data_type;
• Here, pointer-variable is the pointer of type data-type. Data-type could be
any built-in data type including array or any user defined data types
including structure and class.
• Eg: int *p = NULL;
p = new int;
or
int *p = new int;
1. Initialize memory: We can also initialize the memory using new operator:
• Example: int *p = new int(25);
float *q = new float(75.25);
UNIT 2
Information Hiding(Data hiding)
• Information hiding is one of the most important principles of
OOP inspired from real life which says that all information
should not be accessible to all persons. Private information
should only be accessible to its owner.
• “Showing only those details to the outside world which are
necessary for the outside world and hiding all other details
from the outside world.”
• Data Hiding is the one most important OOP mechanism.
Which is hide the details of the class from outside of the class.
• Which mainly includes:-
Encapsulation
Abstraction
• private, public & protected are three types of access specifies
available within a class. the data within a class is private &
the functions are public. The data is hidden, so that it will be
safe from accidental manipulation.
Functions in C++
• A function is a set of statements that take inputs, do some
specific computation and produces output.
• Depending on whether a function is predefined or created by
programmer; there are two types of function:
1. Library Function
2. User-defined Function
Library Function
• Library functions are the built-in function in C++
programming.
• Programmer can use library function by invoking function
directly; they don't need to write it themselves.
• Example: sqrt(), main(), getch() etc.
User-defined Function
• A user-defined function groups code to perform a specific task
and that group of code is given a name(identifier).
• When the function is invoked from any part of program, it all
executes the codes defined in the body of function.
Functions with parameters
• A parameter is a list of variables that is used to pass
information into the function and send information out of
function back to the calling program.
• Parameter is also known as argument.
• There are mainly two modes of parameter passing is given:
1. Actual Parameters
2. Formal Parameters
Actual Parameters :
• The arguments that are passed in a function call are called
actual arguments.
• There is no need to specify datatype in actual parameter.
• Eg: add(num1,num2);
Formal Parameters :
• These are the variables which receives the value from the
function called.
• The datatype of the receiving value must be defined.
• The scope of formal arguments is local to the function definition
in which they are used.
• Eg: int add(int a, int b)
{…….
}
Passing Parameters to a function
by VALUE or by REFERENCE
swap(a, b);
swap(a,b);
//Swapping by PASS BY POINTER
#include<iostream.h>
#include<conio.h>
void swap(int *,int *);
void main()
{ int a=10,b=20;
clrscr();
cout<<"Value of A is: "<<a;
cout<<"\nValue of B is : "<<b;
swap(&a,&b);
INLINE FUNCTION
• C++ provides an inline functions to reduce the function call overhead.
• Inline function is a function that is expanded in line when it is called.
• When the inline function is called whole code of the inline function gets
inserted or substituted at the point of inline function call.
• This substitution is performed by the C++ compiler at compile time.
• Inline function may increase efficiency if it is small.
• SYNTEX:
inline return-type function-name(parameters)
{
// function code;
}
#include <iostream>
int main()
{ cout << “Maximum is=“<<Max(20,10) << endl;
cout << "Maximum is="<< Max(400,200) << endl;
return 0;
}
inline int Max(int x, int y)
{ return (x > y)? x : y;
}
• Inlining is only a request to the compiler, not a command. Compiler
can ignore the request for inlining. Compiler may not perform
inlining in such circumstances like:
}
};
void main()
{
employee e1,e2,e3;
e1.getdata(); //first employee data inserted.
e1.putdata(); //first employee data printed.
e2.getdata(); //second employee data inserted.
e2.putdata(); //second employee data printed.
e3.getdata(); //third employee data inserted.
e3.putdata(); //third employee data printed.
getch();
}
void main()
{ int i;
employee e[3]; //Creating Array of 3 Employees
for(i=0;i<3;i++)
{ cout<<"\n Enter details of "<<" Employee";
e[i].getdata();
}
cout<<"\nDetails of Employees";
for(i=0;i<3;i++)
{ e[i].putdata();
}
}
Friend Functions
• A friend function of a class is defined outside that class scope but it
has the right to access all private and protected members of the
class.
• Even though the prototypes for friend functions appear in the class
definition, friends are not member functions.
• To declare a function as a friend of a class, precede the function
prototype in the class definition with keyword friend.
• A friend function can be given special grant to access private
and protected members of that class.
• A friend function can be:
a) A method of another class
b) A global function
Declaration of friend function in C++:
class class name
{ ... .. ... friend return type function name(class object); ... .. ...
}
• Argument of the function is the class object.
Friend Function Characteristics
• The friend function is not in class scope.
• It should be declared inside the class with ‘friend’ keyword.
• It is not in class scope. So it cannot be called by objects of
the class.
• It can be called like a normal function.
• Usually, it has class objects as arguments.
• It cannot access member variables or functions directly, but
can only be accessed by the help of the objects of the class.
• It can be declared with any access specifier and the access
specifier does not have any impact on the friend function.
• Friendship cant be inherited.
#include <iostream>
class Box
{ double width;
public:
void setWidth( )
{ cout<<“enter the value of width”;
cin>>width;
}
friend void printWidth( Box );
};
void printWidth( Box b) // friend function definition
{
cout << "Width of box : " << b.width <<endl;
}
int main()
{ Box b; // Main function for the program
b.setWidth();
printWidth( b);
return (0);
}
Constructors in C++
What is constructor?
• A constructor is a special member function of the class which has the
same name as that of the class and it does not have a return type.
• A constructor in C++ is a special method that is automatically called when
an object of a class is created.
How constructors are different from a normal member function?
• Constructor has same name as the class itself.
• Constructors don’t have return type.
• A constructor is automatically called when an object is created.
• A constructor can be parametrized or not.
• If we do not specify a constructor, C++ compiler generates a default
constructor for us (expects no parameters and has an empty body).
Types of Constructors
1. Default Constructors:
• Default constructor is the constructor which doesn’t take any
argument means It has no parameters.
• Default constructor called automatically when the object is
created .
• Note: Even if we do not define any constructor explicitly, the
compiler will automatically provide a default constructor
implicitly.
#include <iostream>
class data
{
public:
data() // Default Constructor created
{ cout<<“default constructor is called”;
}
void display()
{ cout<<“member function of class”;
}
};
int main()
{ data d;
d.display();
return (0);
}
#include <iostream>
class construct
{
public:
int a, b;
construct() // Default Constructor
{
a = 10;
b = 20;
}
};
int main()
{
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 0;
}
2. Parameterized Constructors:
• Constructors that receive arguments/ parameters is called as
parameterized constructors.
• These parameterized constructors are called when the object of the
class is created.
• The parameters are passed to the constructor with the object its self.
Uses of Parameterized constructor:
– It is used to initialize the various data elements of different objects
with different values when they are created.
– It is used to overload constructors.
Can we have more than one constructors in a class?
Yes, It is called Constructor Overloading.
Syntex:
class Name(parameter list)
{
}
#include <iostream.h>
class data
{ public: int a;
data() //default constructor called
{cout<<"default constructor is called"<<endl;
}
data(int x) // parameterized constructor called
{ cout<<"Parameterized Constructor is called"<<endl;
a = x;
}
void print() // normal function called
{ cout<<"The value of a is"<<a<<endl;
}
};
// C++ program to calculate the area of a wall
#include <iostream>
class Wall
{
double length;
double height;
public:
Wall(double len, double hgt) // create parameterized constructor
{ length = len;
height = hgt;
}
double Area()
{ return length * height;
}
};
int main()
{
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
cout << "Area of Wall 1: " << wall1.Area() << endl;
cout << "Area of Wall 2: " << wall2.Area() << endl;
return 0;
}
Copy Constructor:
• The copy constructor is a constructor which creates an object by
initializing it with an object of the same class, which has been created
previously.
The copy constructor is used to −
• Initialize one object from another of the same type.
• Copy an object to pass it as an argument to a function.
• Copy an object to return it from a function.
/*...syntax of destructor....*/
class class_name
{ public:
class_name(); //constructor created.
~class_name(); //destructor created.
}
#include <iostream>
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
• Output:
• Constructor Invoked
• Constructor Invoked
• Destructor Invoked
• Destructor Invoked
Garbage collection
• In computer science, garbage collection (GC) is a form of
automatic memory management.
• The garbage collector, or just collector, attempts to reclaim
garbage, or clears the memory occupied by objects that are
no longer in use by the program.
• Garbage collection was invented by John McCarthy around
1959 to simplify manual memory management.
• Garbage collection is a form of automatic memory
management.
• In C++ the garbage collection is implemented explicitly by using Delete
keyword and destructors.
GC Benefits:
• Improve performance ( manages heap).
• No longer have to implement any code that
Manages the lifetime of any resources.
• It is not possible to leak resources.
GC Algorithm(Working Concept):
• Each application has a set of roots.
• Roots identify storage location which refers to
object on the managed heap or the objects
that are set to be null
Metaclass
• In object-oriented programming, a metaclass is a class whose
instances are classes. Just as an ordinary class defines the behavior
of certain objects, a metaclass defines the behavior of certain
classes and their instances.
• The attributes added to this class are accessible to all its
members.
• Not all object-oriented programming languages support meta
classes.
• meta-class is basically the set of instructions that help you
create that class. This is often used when you want to change
the default behavior of classes.
• The metaclass is implemented by using the concept of
interfaces in language like java. In C++ meta class is
implemented by using abstract class concept.
Abstract Data Types
• ADT is the model of data type which holds:
Properties of the data.
Operations that can be performed on the data.
UNIT 3
C++ Inheritance
• In C++, inheritance is a process in which one object acquires all the
properties and behaviors of its parent object automatically.
• By using inheritance concept we 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.
Reason to implement Inheritance is :
• Code reusability: Now you can reuse the members of your parent class.
So, there is no need to define the member again.
• Less code is required in the class.
Base Classes:-
• Known as the parent class
Derived Classes:-
• Known as child class which is defined as the
class derived from the base class and inherit it
features.
Types Of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multilevel inheritance
5. Hybrid inheritance
Syntax of Derived class:
class derived_class_name : visibility-mode base_class_name
{
// body of the derived class.
}
• Public: When the member is declared as public, it is accessible to all the functions
of the program.
• Private: When the member is declared as private, it is accessible within the class
only.
• Protected: When the member is declared as protected, it is accessible within its
own class as well as the class immediately derived from it.
Visibility of Inherited Members
Example of public, protected and
private inheritance in C++
class base
{ public: int x;
protected: int y;
private: int z;
};
Class Derived1: public base
{ x is public accessible
y is protected accessible
z is not accessible
};
class Derived2: private base
{ x is private not accessible
y is private not accessible
z is not accessible
};
class Derived3: protected base
{ x is protected accessible
y is protected accessible
z is not accessible
};
class Derived4: public Derived3
{ x is not accessible
y is not accessible
z is not accessible
};
Single Inheritance
• Single inheritance is defined as the inheritance in which a derived class is
inherited from the only one base class.
• Where 'A' is the base class, and 'B' is the derived class.
#include <iostream>
using namespace std;
class basic_salary
{
public: int salary = 10,000;
};
class increment: public basic_salary
{
public: int bonus = 5000;
};
int main(void)
{
increment p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
cout<<“Total_salary: "<<p1.salary+p1.bonus<<endl;
return 0;
}
Multilevel Inheritance
return 0;
}
Multiple Inheritance
Multiple inheritance is the process of deriving a new class that
inherits the attributes from two or more classes.
return 0;
}
Hierarchical Inheritance
• When several classes are derived from common base class it is
called hierarchical inheritance.
• In C++ hierarchical inheritance, the feature of the base class is inherited
onto more than one sub-class.
• For example, a car is a common class from which Audi, Ferrari, Maruti etc
can be derived.
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
int main()
{ B obj1; //object of derived class B
C obj2; //object of derived class C
D obj3; //object of derived class D
return 0;
} //end of program
C++ Hybrid Inheritance
• Hybrid inheritance in C++ is the inheritance where a class is derived from
more than one form or combinations of any inheritance.
• It Is also called as multipath inheritance.
• In short, hybrid inheritance is a combination of two or more types of
inheritance.
• For example, by implementing single and multilevel inheritances in the
same program.
class A
{ // body of the class A
};
class B : public A
{ // body of the class B
};
class C
{ // body of the class C
};
Main()
{ D obj1 // object the D class is created.
return 0;
}
Abstract Class
• Abstract Class is a class which contains at least one Pure Virtual function
in it.
• Abstract classes are used to provide an Interface for its sub classes.
• Abstract class can have normal functions and variables along with a pure
virtual function
• Classes inheriting an Abstract Class must provide definition to the pure
virtual function, otherwise they will also become abstract class.
• Abstract classes are essential to providing an abstraction to the code to
make it reusable and extendable.
• Abstract classes cannot be used to instantiate objects(no object is
created).
• Classes that inherit the abstract class is called as concrete classes.
Use of Abstract class
• The purpose of an abstract class is to define a common protocol for a set
of concrete subclasses.
• This is useful when defining objects that share code, abstract ideas, etc.
• The main idea here is code reuse and proper partitioning across classes. It
makes more sense to define a function once in a parent class and use it
again and again in all the derive class.
Pure Virtual Functions in C++
• Pure virtual Functions are virtual functions with no definition.
• They start with virtual keyword and ends with = 0.
• Here is the syntax for a pure virtual function,
• virtual void function Name() = 0;
class number
{ public:
virtual void add() = 0;
};
UNIT 3
Polymorphism in C++
• The process of representing one Thing in multiple
forms is known as Polymorphism.
• Polymorphism is derived from 2 Greek words: poly
and morphs.
• The word "poly" means many and “morphs” means
forms. So polymorphism means MANY FORMS
Real life example of Polymorphism
in C++
• Suppose if you are in class room that time you behave like a student,
when you are in market at that time you behave like a customer, when
you at your home at that time you behave like a son or daughter, Here
one person have different-different behaviors.
Type of Polymorphism
• Polymorphism means more than one function with same name, with
different working.
• Polymorphism can be static or dynamic.
Static Polymorphism:-
• In static polymorphism memory will be allocated at compile-time. Both
function overloading and operator overloading are an examples of static
polymorphism.
• Static polymorphism is also known as early binding and compile-time
polymorphism.
Dynamic Polymorphism:-
• In dynamic polymorphism memory will be allocated at run-time. Virtual
function is an example of dynamic polymorphism.
• Dynamic polymorphism is also known as late binding and run-time
polymorphism.
Compile time polymorphism
• In this method object is bound to the function call at the
compile time itself.
• In C++ programming you can achieve compile time
polymorphism in two way, which is given below;
• Function Overloading And Operator Overloading.
Function overloading
• Function Overloading in C++ can be defined as the process of having
two or more member functions of a class with the same name, but
different in parameters.
• In function overloading, the function can be redefined either by
using
Different types of arguments or
Different number of arguments or
Different sequence or order of argument.
• One of the major advantages of Function overloading is that it
increases the readability of the program because we don’t need to
use different names for the same action again and again.
Example:
1.These two have different number of parameters:
•sum(int num1, int num2)
•sum(int num1, int num2, int num3)
};
int main() x + a.x;
{
sum a1(5); x;
sum a2(4);
a1 a2
a1+a2;
return 0;
}
Output:
• The result of the addition of two objects is : 9
minus(-) operator overload
#include <iostream.h>
using namespace std;
class Distance
{ private: int feet; int inches;
public:
Distance(int f, int i) // Constructor
{
feet = f;
inches = i;
}
void display() // method to display distance
{ cout << "F= " << feet << " I=" << inches <<endl;
}
eat() BREAD for energy eat() GRASS for energy eat() LEAVES for energy
#include <iostream.h>
class Animal
{
public:
void eat() // eat() of the base class
{
cout<<“Animal Eat food for energy";
}
};
class Dog: public Animal
{
public:
void eat() // eat() of the derive class
{
cout<<“Dog Eat bread...";
}
};
int main(void)
{
Dog d;
d.eat(); Output: Dog Eat bread...
return 0;
}
• If we want to print base class function also then we have to do this.
int main()
{
animal a; //Base class object
dog d; //Derived class object
a.eat();
d.eat();
}
Direct access
Indirect access
Pointer of base
*a by the pointer
class
• PROGRAM WITH VIRTUAL KEYWORD • PROGRAM WITHOUT VIRTUAL KEYWORD
#include <iostream.h> #include <iostream.h>
class Animal class Animal
{ {
public: public:
Virtual void eat() // eat() of the base class void eat() // eat() of the base class
{ {
cout<<“Animal Eat food for energy"; cout<<“Animal Eat food for energy";
} }
}; };
class Dog: public Animal class Dog: public Animal
{ {
public: public:
void eat() // eat() of the derive class void eat() // eat() of the derive class
{ {
cout<<“Dog Eat bread..."; cout<<“Dog Eat bread...";
} }
}; };
int main(void) int main(void)
{ {
Animal *a; // pointer object of base class Animal *a; // pointer object of base class
Dog d; //object of derived class Dog d; //object of derived class
a = &d; a = &d;
a->eat(); //Late Binding occurs a->eat(); //Late Binding occurs
return 0; return 0;
} }
UNIT 4
Files and Streams
• In C++ programming we are using the iostream standard library, it
provides cin and cout methods for reading from input and writing to
output respectively.
• To read and write from a file we are using the standard C++ library
called fstream. Let us see the data types define in fstream library is:
How to achieve File Handling
For achieving file handling in C++ we need follow following steps
• Naming a file
• Opening a file
• Reading data from file
• Writing data into file
• Closing a file
Defining and Opening a File
• The function open() can be used to open multiple files that use the same
stream object.
Modes of Opening a file
• We need to tell the computer the purpose of opening our file.
• For e.g.- to write on the file, to read from the file, etc.
• These are the different modes in which we can open a file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open ("example.txt", ios::out | ios::in );
return 0;
}
Closing a File
• A file must be close after completion of all operation related to file. For
closing file we need close() function.
Reading &Writing in a FILE
Writing in a file…
File is created in bin(folder)
Demo file data
Reading from a file
Namespaces
• Namespaces in C++ are used to organize too many classes so that it can be
easy to handle the application.
• For accessing the class of a namespace, we need to use
namespacename::classname. We can use using keyword so that we don't
have to use complete name all the time.
• In C++, global namespace is the root namespace. The global::std will
always refer to the namespace "std" of C++ Framework.
#include <iostream.h>
using namespace std;
namespace First
{
void sayHello()
{
cout<<"Hello First Namespace"<<endl;
}
}
namespace Second
{
void Hello()
{
cout<<"Hello Second Namespace"<<endl;
}
}
int main()
{
First::sayHello();
Second::Hello();
return 0;
}
OUTPUT: Hello First Namespace
Hello Second Namespace
Exception Handling
• Exception Handling in C++ is a process to handle runtime errors.
• We perform exception handling so the normal flow of the application can be maintained
even after runtime errors.
• In C++, exception is an event or object which is thrown at runtime.
• All exceptions are derived from (std::exception class).
• It is a runtime error which can be handled. If we don't handle the exception, the
program will terminate automatically without any message else, it prints exception
message and terminates the program.
Advantage
• It maintains the normal flow of the application. In such case, rest of the code is executed
even after exception.
return 0;
}
//program for checking number divided by (ZERO)….
#include<iostream>
using namespace std;
int main()
{ int var1=10, var2=0; float var3;
try
{ if(var2!=0)
{ var3=var1/var2;
cout<<"outcome :"<<var3;
}
else
{ throw(var2);
}
}
catch(int exc)
{ cout<<"division by zero is not possible. Please try again with different
value of variables";
}
}
Templates
}
int main()
{
int i =2, j =3, s=0;
float m = 2.3, n = 1.2, a=0;
s = add(i,j);
cout<<"Addition of i and j is :"<< s;
cout<<'\n';
a= add(m,n);
cout<<"Addition of m and n is :"<< a;
return 0;
}
• Output: Addition of i and j is : 5 Addition of m and n is : 3.5
2.CLASS TEMPLATE
Class Template:-
• class templates are useful when a class defines something that is
independent of the data type.
• When a class uses the concept of Template, then the class is known as
generic class.
Syntax
template<class Ttype>
class class_name
{
.
.
}
Ttype is a placeholder name which will be determined when the class is
instantiated. We can define more than one generic data type using a comma-
separated list. The Ttype can be used inside the class body.
• Now, we create an instance of a class i.e. OBJECT
SYNTEX
class_name<type> ob;
Where:
• class_name: It is the name of the class.
• type: It is the type of the data that the class is operating on.
• ob: It is the name of the object.
#include <iostream>
template<class T>
class Addition
{
public:
T add(T num1, T num2)
{
cout << "Addition of num1 and num2 : " << num1+num2<<endl;
}
};
int main()
{
Addition<int>a1;
Addition<long>a2;
a1.add( 10,20);
a2.add(5.5,4.5);
return 0;
}
How to create User define Header
•
file..
Write a program which you want to store in a header file:
int sum(int a, int b)
{ return (a + b);
}
#include <iostream.h>
#include <sum.h>
using namespace std;
int main()
{ int a = 10, b = 20; // Given two numbers
cout << "Sum is: "<< sum(a, b) << endl;
}