C++ Second Internal Study Material
C++ Second Internal Study Material
Define- Inheritance:
inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically
Types Of Inheritance
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.
1. class derived_class_name :: visibility-mode base_class_name
2. {
3. // body of the derived class.
4. }
Where,
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.
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.
Example Program:
#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
Output:
Salary: 60000
Bonus: 5000
Visibility modes can be classified into three categories:
o Public: When the member is declared as public, it is accessible to all the functions of the program.
o Private: When the member is declared as private, it is accessible within the class only.
o Protected: When the member is declared as protected, it is accessible within its own class as well
as the class immediately derived from it.
Multiple inheritance is the process of deriving a new class that inherits the attributes from two or
more classes.
class D : visibility B-1, visibility B-2, ?
{
// Body of the class;
}
Example Program:
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
}
};
class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
std::cout << "The value of a is : " <<a<< std::endl;
std::cout << "The value of b is : " <<b<< std::endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
int main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();
return 0;
}
C++ 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.
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
} };
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
} };
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a()
{
std::cout << "Enter the value of 'a' : " << std::endl;
cin>>a;
}
};
class B : public A
{
protected:
int b;
public:
void get_b()
{
std::cout << "Enter the value of 'b' : " << std::endl;
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
std::cout << "Enter the value of c is : " << std::endl;
cin>>c;
}
};
class D : public B, public C
{
protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
}
};
int main()
{
D d;
d.mul();
return 0;
}
C++ Hierarchical Inheritance
Hierarchical inheritance is defined as the process of deriving more than one class from a base class.
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.
}
C++ Constructor
Constructor is a special method which is invoked automatically at the time of object creation.
Types of Constructors
Syntax:
class_name()
{
// constructor Definition
}
For example:
class Cube
{
public:
int side;
Cube()
{
side = 10;
}
};
int main()
{
Cube c;
cout << c.side;
}
Syntax:
Example:
class Cube
{
public:
int side;
Cube(int x)
{
side=x;
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
COPY Constructor
Copy Constructor is a type of constructor which is used to create a copy of an already existing
object of a class type.
It is usually of the form X (X&), where X is the class name.
The compiler provides a default Copy Constructor to all the classes.
Syntax:
#include<iostream>
using namespace std;
class Samplecopyconstructor
{
private:
int x, y; //data members
public:
Samplecopyconstructor(int x1, int y1)
{
x = x1;
y = y1;
}
/* Copy constructor */
Samplecopyconstructor (const Samplecopyconstructor &sam)
{
x = sam.x;
y = sam.y;
}
void display()
{
cout<<x<<" "<<y<<endl;
}
};
/* main function */
int main()
{
Samplecopyconstructor obj1(10, 15); // Normal constructor
Samplecopyconstructor obj2 = obj1; // Copy constructor
cout<<"Normal constructor : ";
obj1.display();
cout<<"Copy constructor : ";
obj2.display();
return 0;
}
OUTPUT:
Normal constructor : 10 15
Copy constructor : 10 15
C++ 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 (~).
C++ destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.
Example Program:
#include <iostream>
using namespace std;
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
C++ this Pointer
this is a keyword that refers to the current instance of the class. There can be 3 main usage of this
keyword in C++.
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void)
{
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
e1.display();
e2.display();
return 0;
}
C++ virtual function
o A C++ virtual function is a member function in the base class that you redefine in a derived
class. It is declared using the virtual keyword.
o It is used to tell the compiler to perform dynamic linkage or late binding on the function.
o There is a necessity to use the single pointer to refer to all the objects of the different classes.
So, we create the pointer to the base class that refers to all the derived objects. But, when base
class pointer contains the address of the derived class object, always executes the base class
function. This issue can only be resolved by using the 'virtual' function.
o A 'virtual' is a keyword preceding the normal declaration of a function.
Example Program:
#include <iostream>
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}
Output:
o A virtual function is not used for performing any task. It only serves as a placeholder.
o When the function has no definition, such function is known as "do-nothing" function.
o The "do-nothing" function is known as a pure virtual function. A pure virtual function is a
function declared in the base class that has no definition relative to the base class.
Syntax:
o Data Abstraction is a process of providing only the essential details to the outside world and
hiding the internal detail.
o Representing only the essential details in the program.
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.
Unformatted consol input output operations
The following are operations of unformatted consol input / output operations:
A) void get()
It is a method of cin object used to input a single character from keyboard. But its main property is that
it allows wide spaces and newline character.
Syntax:
char c=cin.get();
Example:
#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout<<c<<endl;
return 0;
}
B) void put()
It is a method of cout object and it is used to print the specified character on the screen or monitor.
Syntax:
cout.put(variable / character);
Example:
#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout.put(c); //Here it prints the value of variable c;
cout.put('c'); //Here it prints the character 'c';
return 0;
}
C) getline(char *buffer,int size)
This is a method of cin object and it is used to input a string with multiple spaces.
Syntax:
char x[30];
cin.getline(x,30);
Example:
#include<iostream>
using namespace std;
int main()
{
cout<<"Enter name :";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout<<c<<endl;
return 0;
}
It is a method of cout object. This method is used to read n character from buffer variable.
Syntax:
cout.write(x,2);
Example:
#include<iostream>
using namespace std;
int main()
{
cout<<"Enter name : ";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout.write(c,9); //It reads only 9 character from buffer c;
return 0;
}
E) cin
Syntax:
cin>>variable
F) cout
Syntax:
A) width(n)
Syntax:
cout<<setw(int n);
B) fill(char)
Syntax:
cout<<setfill('character')<<variable;
D) precison(n)
Syntax:
cout<<setprecision('int n')<<variable;
E) setflag(arg 1, arg,2)
F) unsetflag(arg 2)
Syntax:
resetiosflags(argument 2);
G) setbase(arg)
Syntax:
setbase(argument);
Managing Output with Manipulators
endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes
ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.
ends: It is also defined in ostream and it inserts a null character into the output stream
flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output
written on the screen or in the file. Without flush, the output would be the same, but may not
appear in real-time.
ofstream
1
This data type represents the output file stream and is used to create files and to write
information to files.
ifstream
2
This data type represents the input file stream and is used to read information from files.
fstream
3 This data type represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files, and
read information from files.
Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And ifstream object
is used to open a file for reading purpose only.
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
void close();
Detecting end-of-file
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.
o Function templates
o Class templates
Function Template
o Generic functions use the concept of a function template. Generic functions define a set of
operations that can be applied to the various types of data.
o The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
o A Generic function is created by using the keyword template. The template defines what
function will do.
Syntax:
template < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}
Example program:
#include <iostream>
using namespace std;
template<class T> T add(T &a,T &b)
{
T result = a+b;
return result;
}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<'\n';
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
Syntax
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of function.
}
Example:
#include <iostream>
using namespace std;
template<class X,class Y> void fun(X a,Y b)
{
std::cout << "Value of a is : " <<a<< std::endl;
std::cout << "Value of b is : " <<b<< std::endl;
}
int main()
{
fun(15,12.3);
return 0;
}
Overloading a Function Template
We can overload the generic function means that the overloaded template functions can differ in
the parameter list.
Example Program:
#include <iostream>
using namespace std;
template<class X> void fun(X a)
{
std::cout << "Value of a is : " <<a<< std::endl;
}
template<class X,class Y> void fun(X b ,Y c)
{
std::cout << "Value of b is : " <<b<< std::endl;
std::cout << "Value of c is : " <<c<< std::endl;
}
int main()
{
fun(10);
fun(20,30.5);
return 0;
}
CLASS TEMPLATE:
Class Template can also be defined similarly to the Function Template. When a class uses the
concept of Template, then the class is known as generic class.
Syntax:
template<class Ttype>
class class_name
{
.
}
Example:
#include <iostream>
using namespace std;
template<class T>
class A
{
public:
T num1 = 5;
T num2 = 6;
void add()
{
std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;
}
};
int main()
{
A<int> d;
d.add();
return 0;
}
CLASS TEMPLATE WITH MULTIPLE PARAMETERS
We can use more than one generic data type in a class template, and each generic data type is
separated by the comma.
Syntax
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}
Example Program:
#include <iostream>
using namespace std;
template<class T1, class T2>
class A
{
T1 a;
T2 b;
public:
A(T1 x,T2 y)
{
a = x;
b = y;
}
void display()
{
std::cout << "Values of a and b are : " << a<<" ,"<<b<<std::endl;
}
};
int main()
{
A<int,float> d(5,6.5);
d.display();
return 0;
}
Nontype Template Arguments
The template can contain multiple arguments, and we can also use the non-type arguments In
addition to the type T argument, we can also use other types of arguments such as strings,
function names, constant expression and built-in types.
Syntax:
template<class T, int size>
class array
{
T arr[size]; // automatic array initialization.
};
Example Program:
#include <iostream>
using namespace std;
template<class T, int size>
class A
{
public:
T arr[size];
void insert()
{
int i =1;
for (int j=0;j<size;j++)
{
arr[j] = i;
i++;
}
}
void display()
{
for(int i=0;i<size;i++)
{
std::cout << arr[i] << " ";
}
}
};
int main()
{
A<int,10> t1;
t1.insert();
t1.display();
return 0;
}
C++ 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.
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,
it prints exception message and terminates the program.
Exception Description
o try
o catch, and
o throw
try block:
The code which can throw any exception is kept inside(or enclosed in) atry block. Then, when the
code will lead to any error, that error/exception will get caught inside the catch block.
catch block
catch block is intended to catch the error and handle the exception condition. We can have multiple catch
blocks to handle different types of exception and perform different actions when the exceptions occur.
throw statement
It is used to throw exceptions to exception handler i.e. it is used to communicate information about error.
A throw expression accepts one parameter and that parameter is passed to handler.
throw statement is used when we explicitly want an exception to occur, then we can use throw statement to
throw or generate that exception.
Syntax:
try
{
//code
throw parameter;
}
catch(exceptionname ex)
{
//code to handle exception
}
Example Program:
include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int a=10, b=0, c;
// try block activates exception handling
try
{
if(b == 0)
{
// throw custom exception
throw "Division by zero not possible";
c = a/b;
}
}
catch(char* ex) // catches exception
{
cout<<ex;
}
return 0;
}
OUTPUT:
Division by zero not possible
Multiple catch blocks:
We can use more than one catch blocks in a single program
Syntax:
try
{
//code
}
catch(exceptionname ex1)
{
//code to handle exception
}
catch(exceptionname ex2)
{
//code to handle exception
}
Example Program:
#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int x[3] = {-1,2};
for(int i=0; i<2; i++)
{
int ex = x[i];
try
{
if (ex > 0)
// throwing numeric value as exception
throw ex;
else
// throwing a character as exception
throw 'ex';
}
catch (int ex) // to catch numeric exceptions
{
cout << "Integer exception\n";
}
catch (char ex) // to catch character/string exceptions
{
cout << "Character exception\n";
}}}
OUTPUT:
Integer exception
Character exception
Catch All Exception:
Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.
Syntax:
try
// ...
} catch (...)
{
// ...
}
Example Program:
#include <iostream>
using namespace std;
void func(int a) {
try {
if(a==0) throw 23.33;
if(a==1) throw 's';
} catch(...) {
cout << "Caught Exception!\n";
}
}
int main() {
func(0);
func(1);
return 0;
}
Output
Caught Exception!
Caught Exception!
Rethrowing an Exception
Rethrowing an expression from within an exception handler can be done by calling throw, by itself,
with no exception.
This causes current exception to be passed on to an outer try/catch sequence. An exception can only be
rethrown from within a catch block.
Example Program:
#include <iostream>
using namespace std;
void MyHandler()
{
try
{
throw “hello”;
}
catch (const char*)
{
cout <<”Caught exception inside MyHandler\n”;
throw; //rethrow char* out of function
}
}
int main()
{
cout<< “Main start”;
try
{
MyHandler();
}
catch(const char*)
{
cout <<”Caught exception inside Main\n”;
}
cout << “Main end”;
return 0;
}
Output :
Main start
Caught exception inside MyHandler
Caught exception inside Main
Main end