C++ Programming Language Overview
C++ Programming Language Overview
• It is of two type:
1. Top-Down Approach.
2. Bottom-Up Approach.
Designed By: VASUDHA
Designed By: VASUDHA
Designed By: VASUDHA
Top-Down Approach of Problem
Solving
Working approach:
• Breakdown the main problem into sub problems.
• Refining each sub problems into much smaller sub
problems.
• We Continue this process until every part is simple
enough to implement or solve.
OBJECTS
• In C++, Object is a real-world entity, for example, chair, car,
pen, mobile, laptop etc.
• In other words, object is an entity that has state and behavior.
Here, state means data and behavior means functionality.
• Object is a runtime entity it is created at runtime.
• Object is an instance of a class. When a class is defined, no
memory is allocated but when it is instantiated (i.e. an object
is created) memory is allocated .
• All the data members and member function defined in the
class can be accessed through object using dot (.) operator.
• Before create an objects and use them in C++, we first need
to create a classes.
2. Multiple Inheritance: In this there is only one derive class which inherit the
features from more than one base class.
Function overriding:
• Function overriding is only possible within an
inheritance, where the function of the derived
class override the function of the base class.
• Both the functions have same name, return type,
and parameters list. The decision of which
version of the function (base or derived) to
execute is made at runtime.
Designed By: VASUDHA
Advantages and Disadvantages of Object Oriented
Programming Language
ADVANTAGES:
• High Performance and Efficient memory
management.
• Support Object-Oriented Programming (OOP)
concepts.
• Highly portable language.
• Provides direct memory access through pointers.
• Support different libraries, frameworks, and tools
that can accelerate development and simplify
complex tasks.
• The general syntax is: #include <header file> .or #include "header file"
For example: #include <iostream.h>, #include <conio.h> , #include "dos.h“
2. 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
3. Member Functions
• These are the various operations that can be performed to data members
of that class.
• Member functions are access using object and dot operator.
• example: void read(), void display()
Designed By: VASUDHA
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:
[Link]: 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.
2. Public: Public members are accessible from outside the class.
[Link]: 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( )
{Circle c2; //Object created inside main
}
}
};
main ( ) // Main program
{
clrscr();
Display d1; // Object of the class is created
[Link]( ); //Member functions is accessed through object.
[Link]( );
getch( );
Designed By: VASUDHA
}
OPERATORS IN C++
#include<iostream.h>
int x=30; // Global x
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;
} Designed By: VASUDHA
2) To define a function outside a class.(Accessing members of
a class from outside the class definition )
Class num
{ public:
static int var1;
};
int num::var1 = 5; // Definition of static member
int main()
{
cout << num::var1 << endl; // Accessing static member
return 0;
}
Designed By: VASUDHA
4) Accessing members within a namespace:
• Namespaces are used to organize code and prevent
naming conflicts. The scope resolution operator is
used to access identifiers within a specific namespace.
#include<iostream.h>
#include<conio.h>
Using namespace std;
Int main()
{ std::cout<<“hello world”;
getch();
}
Examples:
• delete p;
• delete q;
UNIT 2
Designed by:Vasudha
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.
Designed by:Vasudha
Designed by:Vasudha
Common examples of ADTs include:
•List: A sequence of elements with operations like insert, delete, access,
and search
•Stack: A LIFO (Last-In, First-Out) structure with operations like
•push (add an element).
•pop (remove the most recent element).
•Queue: A FIFO (First-In, First-Out) structure with operations like
•enqueue (add an element to the rear).
•dequeue (remove an element from the front).
•peek (retrieves the element at the front (or head) of the queue without
removing it). Designed by:Vasudha
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
Designed by:Vasudha
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.
Designed by:Vasudha
Designed by:Vasudha
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
Designed by:Vasudha
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)
{…….
}
Designed by:Vasudha
Designed by:Vasudha
Passing Parameters to a function by VALUE or by
REFERENCE Method:
Designed by:Vasudha
#include <iostream.h> Call by Value
#include <conio.h>
class Swap
{ public:
void SwapByValue(int num1, int num2)
{ int temp = num1;
num1 = num2;
num2 = temp;
cout << ‘Swapped value:”<<num1<<num2 << endl;
}
};
int main()
{ Swap s;
int a = 5, b = 10;
cout << "Before swapping: a = " << a << ", b = " << b << endl;
s. SwapByValue(a, b);
cout << "After swapping: a = " << a << ", b = " << b << endl;
getch();
return 0;
}
Designed by:Vasudha
2. Call by reference(Pass by reference)
• In this method of passing arguments to a
function copies the reference of an actual
argument into the formal parameter.
• Any changes to the formal parameter are
reflected in the actual parameter in the
calling environment as formal parameter
receives a reference (or pointer) to the
actual data.
• This method is efficient in both time and
space.
Designed by:Vasudha
Call by Reference
#include <iostream.h>
#include <conio.h>
class Swap
{ public:
void swapByReference(int &num1, int &num2)
{ int temp = num1;
num1 = num2;
num2 = temp;
cout << ‘Swapped value:”<<num1<<num2 << endl;
}
};
int main()
{ Swap s;
int a = 5, b = 10;
cout << "Before swapping: a = " << a << ", b = " << b << endl;
[Link](a, b);
cout << "After swapping: a = " << a << ", b = " << b << endl;
getch();
return 0;
} Designed by:Vasudha
INLINE FUNCTION
• In inline function the compiler is advised to insert the function's
body directly into each place where the function is called, rather
than performing a traditional function call. It is also known as
inlining.
• Aims to reduce the overhead associated with function calls like
pushing arguments onto the stack, jumping to the function's address,
and returning is eliminated.
• The inline keyword is a suggestion to the compiler, not a
command. The compiler may choose to ignore the inline keyword for
large or complex functions, or functions with loops or recursion.
• This substitution is performed by the C++ compiler at compile time.
• Inline function may increase efficiency if the Code is small.
• SYNTEX:
inline return-type function-name(parameters)
{
// function code;
}
Designed by:Vasudha
Designed by:Vasudha
#include <iostream.h>
inline int cube(int c)
{
return c*c*c;
}
int main()
{ int value, n;
Cout<<“enter the number”;
Cin>>n;
Value= cube(n);
cout << "The cube of n=“<<value<<endl;
return 0;
} Designed by:Vasudha
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 global function
b)A method of another class
Designed by:Vasudha
Designed by:Vasudha
Declaration of friend function in C++:
class class_name
{ ... .. ... friend return type function name(class object); ... .. ...
}
Designed by:Vasudha
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 can't be inherited.
Designed by:Vasudha
1. Global Function as Friend Function
#include <iostream.h>
class Box
{ double width;
public:
void setWidth( )
{ cout<<“enter the value of width”;
cin>>width;
}
friend void print( Box ); // Friend function is Defined.
};
#include <iostream>
//CLASS 1 IS CREATED /CLASS 2 IS CREATED
class base class print
{ public: int p1,p2; {
public: public:
void setvalue() void print_function(base b)
{ p1=10; {
p2=99; cout << "Variable1 value: "<< b.p1<< endl;
} cout << "Variable2 value: "<< b.p2;
friend void print_function(base); }
};
};
int main()
{
base b1;
print p3;
[Link]();
p3.print_function(b1);
return 0;
}
Designed by:Vasudha
• Friend Class Example:
#include <iostream.h>
//CLASS 1 IS CREATED
//CLASS 2 IS CREATED
class Data
class print
{
{
int i =3;
public:
friend class print;
void display(data d)
};
{cout<<"The value of i is : "<<d.i;
}
int main()
};
{
Data d;
print p;
[Link](d);
return 0;
}
Designed by:Vasudha
OBJECT
• Object is a real world entity.
• An object has state, behavior, and identity; the structure and
behavior of similar objects are defined in their common class.”
Designed by:Vasudha
1. Passing Object as an argument in
C++ function
• In any programming language we can pass any
type of arguments within the member function
and there are any numbers of arguments.
Syntax:
function_name(object_name);
Designed by:Vasudha
// WAP which take values from the objects and perform the sum and display it.
# include<iostream.h>
class Demo
{ private: int a;
public:
void set(int x)
{ a = x;
}
void sum(Demo d1, Demo d2)
{ a = d1.a + d2.a;
}
void print()
{ cout<<"Value of a : "<< a <<endl;
}
};
int main()
{ Demo d1,d2, d3;
[Link](10); //Message Passing
[Link](20); //Message Passing
[Link](d1,d2); //passing object d1 and d2
[Link]();
[Link]();
[Link]();
return 0;
} Designed by:Vasudha
Output
• Value of A : 10
• Value of A : 20
• Value of A : 30
Designed by:Vasudha
#include <iostream.h>
class Total
{
public: int a;
public: void add(Total E)
{ a = a + E.a;
}
};
int main()
{
Total E1, E2;
E1.a = 50; // Values are initialized for both objects
E2.a = 100;
cout << "Initial Values \n";
cout << "Value of object 1: " << E1.a << "\n& object 2: " << E2.a << "\n\n";
[Link](E1); // Passing object as an argument to function add()
cout << "New values \n";
cout << "Value of object 1: " << E1.a << "\n& object 2: " << E2.a << "\n\n";
return 0; }
Designed by:Vasudha
• Output:
Initial Values Value of
object 1: 50 & object 2: 100
New values Value of
object 1: 50 & object 2: 150
Designed by:Vasudha
2. Array of Objects in C++
SYNTEX:
• ClassName ObjectName[Number of Objects];
Designed by:Vasudha
Designed by:Vasudha
class employee
{public: int id;
char name[25];
int age;
long salary;
public:
void getdata()
{ cout<<"Enter Employee Id : ";
cin>>id;
cout<<"Enter Employee Name : ";
cin>>name;
cout<<"Enter Employee Age : ";
cin>>age;
cout<<"Enter Employee Salary : ";
cin>>salary;
}
void putdata()
{ cout<<“ID of employee”<<id<<endl;
cout<<“Name of employee”<<name<<endl;
cout<<“Age of employee”<<age<<endl;
cout<<“Salary of employee”<<salary<<endl;
}
};
Designed by:Vasudha
void main()
{
employee e1,e2,e3;
[Link](); //first employee data inserted.
[Link](); //first employee data printed.
[Link](); //second employee data inserted.
[Link](); //second employee data printed.
[Link](); //third employee data inserted.
[Link](); //third employee data printed.
getch();
}
Designed by:Vasudha
void main()
{ int i;
employee e[3]; //Creating Array of 3 Employees
for(i=0;i<3;i++)
{ cout<<"\n Enter the details of Employee";
e[i].getdata();
}
cout<<"\nDetails of Employees are";
for(i=0;i<3;i++)
{ e[i].putdata();
}
}
Designed by:Vasudha
Constructors in C++
What is constructor?
• A constructor is a special member function of the class that is
automatically called when an object of a class is created.
• Same Name as Class: Constructor has same name as the class itself.
• No Return Type: Constructors do not have a return type, not even
(void).
• Automatic Invocation: They are called implicitly by the compiler when
an object is instantiated, unlike regular member functions that require
explicit called.
• Different Type: A constructor can be created with parameter or without .
• If we do not specify a constructor, C++ compiler generates a default
constructor for us (expects no parameters and has an empty body).
Designed by:Vasudha
Designed by:Vasudha
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.
Designed by:Vasudha
#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;
[Link]();
return (0);
}
Designed by:Vasudha
#include <iostream>
class number
{
public:
int a, b;
number() // Default Constructor
{
a = 10;
b = 20;
}
};
int main()
{
number c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 0;
}
Designed by:Vasudha
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 different objects with different values
when they are created.
Can we have more than one constructors in a class?
Yes, It is called Constructor Overloading.
Syntex:
class Name(parameter list)
{
}
Designed by:Vasudha
#include<iostream>
class data
{ public: int a;
Designed by:Vasudha
// 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;
}
}; Designed by:Vasudha
int main()
{
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
cout << "Area of Wall 1: " << [Link]() << endl;
cout << "Area of Wall 2: " << [Link]() << endl;
return 0;
}
Designed by:Vasudha
.
3. Copy Constructor:
• A copy constructor is a member function that
initializes an object using another object of the
same class.
• Copy constructor takes a reference to an object
of the same class as an argument.
Designed by:Vasudha
Purpose of a Copy Constructor
• a copy constructor is to ensure a proper and independent copy of
an object, especially when the object contains dynamically
allocated memory or other resources.
Designed by:Vasudha
#include<iostream.h> int main()
class Point {
{ private: int x, y; Point p1(10,15);
public: Point p2=p1; // Copy constructor
Point(int x1, int y1) is called here
{ x = x1; p1.print_value();
y = y1; p2.print_value();
} return 0;
Point(const Point &p1) // Copy }
constructor
{ x = p1.x;
y = p1.y;
}
void print_value()
{ cout<<"\nvalue of x="<<x;
cout<<"\nvalue of y="<<y;
}
}; Designed by:Vasudha
Destructors in C++
• What is destructor?
Destructor is a member function which destructs or deletes an object.
Designed by:Vasudha
• When do we need to write a user-defined destructor?
If we do not write our own destructor in class, compiler
creates a default destructor for us. The default destructor
works fine unless we have dynamically allocated memory or
pointer in class.
/*...syntax of destructor....*/
class class_name
{ public:
class_name(); //constructor created.
~class_name(); //destructor created.
}
Designed by:Vasudha
#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;
} Designed by:Vasudha
• Output:
• Constructor Invoked
• Constructor Invoked
• Destructor Invoked
• Destructor Invoked
Designed by:Vasudha
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.
Designed by:Vasudha
Designed by:Vasudha
Designed by:Vasudha
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.
Designed by:Vasudha
Meta Class
• In object-oriented programming, a meta class refers to a class
that defines or generates other classes.
• It is a class whose instances are classes. Normally a class has
an instance as an objects.
• Not all object-oriented programming languages support meta
classes.
• Meta-class is basically the set of instructions that help you
create that class.
• 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.
Designed by:Vasudha
Designed by:Vasudha
INHERITANCE
UNIT 3
Designed by:Vasudha
Inheritance
Designed by:Vasudha
Syntax of Derived class:
class derived_class_name : visibility-mode base_class_name
{
// body of the derived class.
}
Designed by:Vasudha
How to make a Private Member
Inheritable
• C++ introduces a third visibility modifier, i.e., protected. The member
which is declared as protected will be accessible to all the member
functions within the class as well as the class immediately derived from it.
Designed by:Vasudha
Visibility of Inherited Members
Designed by:Vasudha
Types Of Inheritance
1. Single Inheritance: A derived class inherits from a
single base class.
2. Multiple Inheritance: A derived class inherits from
multiple base classes.
3. Multilevel Inheritance: A class inherits from
another derived class, forming a chain of
inheritance.
4. Hierarchical Inheritance: Multiple derived classes
inherit from a single base class.
5. Hybrid Inheritance: A combination of two or more
types of inheritance.
Designed by:Vasudha
Example of public, protected and
private inheritance in C++
Designed by:Vasudha
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
};
Designed by:Vasudha
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
};
Designed by:Vasudha
Designed by:Vasudha
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.
Designed by:Vasudha
int main()
#include <iostream.h>
{
increment i;
class basic_salary //BASE CLASS cout<<"Salary: "<<[Link]<<endl;
{ cout<<"Bonus: "<<[Link]<<endl;
public: int salary;
basic_salary() int Total_salary=[Link] + [Link];
{salary = 10,000;
} cout<< “Total salary=“<< Total_salary;
}; return 0;
class increment: public basic_salary }
//DERIVE CLASS
{
public: int bonus;
increment()
{ bonus = 5000;
};
Designed by:Vasudha
Multiple Inheritance
Multiple inheritance is the process of deriving a new class that
inherits the attributes from two or more classes.
Designed by:Vasudha
#include <iostream>
Designed by:Vasudha
class add : public num1 , public num2
{
public: int sum;
void display()
{
cout << "The value of a is : " <<a<< endl;
cout << "The value of b is : " <<b<< endl;
sum=a+b ;
cout<<"Addition of a and b is : "<<sum;
}
};
int main()
{
add c;
c.get_a(10);
c.get_b(20);
[Link]();
return 0;
}
Designed by:Vasudha
Multilevel Inheritance
• Multilevel inheritance is a process of deriving a class from another
derived class.
• 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.
Designed by:Vasudha
#include<iostream.h>
class num //SUPER BASE CLASS
{ protected: int a,b;
public:
void getdata()
{ cout<<"enter first number=";
cin>>a;
cout<<"enter second number=";
cin>>b;
}
protected:
void protectedfunction()
{ cout<<"\nprotected function of base class is called";
}
}; Designed by:Vasudha
class add:public num // Derived Class 1
{ public:
int add;
public:
void sum()
{ add= a+b;
cout<<"value of addition:"<<add;
}
protectedfunction();
};
Designed by:Vasudha
class percent: public add // Derived Class 2
{ public: int per;
public:
void percentage()
{ per= ((add/200)*100);
cout<<"\nvalue of a="<<a;
cout<<"\nvalue of b="<<b;
cout<<"\nvalue of sum="<<add;
cout<<"\n value of percentage="<<per;
protectedfunction();
}
};
int main()
{ percent p;
[Link]();
[Link]();
[Link]();
return 0;
}
Designed by:Vasudha
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.
Designed by:Vasudha
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;
}
Designed by:Vasudha
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.
Designed by:Vasudha
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;
}
Designed by:Vasudha
Abstract Class
• Abstract Class is a class which contains at least one Pure
Virtual function in it.
• Abstract class can have normal functions and variables along
with a pure virtual function
• Classes that inherit the abstract class is called as concrete
classes.
• Cannot be Instantiated: You cannot create objects of an
abstract class directly. Attempting to do so will result in a
compilation error.
• Serves as a Base Class: Abstract classes are primarily used as
base classes for inheritance. Derived classes inherit from the
abstract class and must provide implementations for all its
pure virtual functions, or they too will become abstract..
Designed by:Vasudha
Key characteristics of an abstract class:
• Pure Virtual Functions: An abstract class must
contain at least one pure virtual function.
• A pure virtual function is declared by
assigning = 0 in its declaration, indicating that
it has no implementation in the base class.
• Derived classes are then required to provide
an implementation for these pure virtual
function.
Designed by:Vasudha
class number
{ public:
virtual void add() = 0;
};
Designed by:Vasudha
#include<iostream.h>
class Base //Abstract base class
{ public:
virtual void show() = 0; // Pure Virtual Function
};
Int main()
{
Derived d;
[Link]();
}
Designed by:Vasudha
class color
{ public: virtual void showcolor() = 0; // pure virtual function
};
class red:public color
{ public: void showcolor()
{ cout << "color is red"<<endl;
}
};
class blue:public color
{ public: void showcolor()
{ cout << "color is blue"<<endl;
}
};
int main()
{ red r;
blue b;
[Link]();
[Link](); } Designed by:Vasudha
Designed by:Vasudha
Relations between CLASSES
• The relationship between the classes explains
how the classes are connected to each other’s
and how they will behave.
• Mainly there are four type of relationship is
present :
Inheritance
Association
Aggregation
Composition
Designed by:Vasudha
• Inheritance:
• One class can use features from another class to access its
functionality.
• Inheritance based on IS-A Relationship.
• Inheritance is uni-directional. Inheritance is indicated by
a solid line with a arrowhead pointing at the super class.
Designed by:Vasudha
Association
• Association represents a relationship between two or
more objects where all objects have their own life
cycle and there is no owner.
• Association is based on HAS-A Relationship.
• Association can be one-to-one, one-to-many, many-
to-one, many-to-many.
• Composition and Aggregation are the two forms of
association.
Designed by:Vasudha
• In above example two separate classes Bank
and Employee are associated through their
Objects. Bank can have many employees, So it
is a one-to-many relationship.
Designed by:Vasudha
Designed by:Vasudha
Aggregation
• Aggregation is a special form of Association where all objects have their
own life cycle but there is ownership.
• This represents a-part-of relationship based on HAS-A Relationship.
• This is represented by a hollow diamond followed by a line.
• In Aggregation, both the entries can survive individually which means
ending one entity will not effect the other entity
Designed by:Vasudha
Composition
• Composition is a restricted form of Aggregation in which two entities are
highly dependent on each other.
• It represents part-of-death relationship, in this both the entities are
dependent on each other.
• When there is a composition between two entities, the composed object
cannot exist without the other entity.
• This is represented by a solid diamond followed by a line.
Designed by:Vasudha
POLYMORPHISM
UNIT 3
Designed by:Vasudha
Polymorphism in C++
• The process of representing one Thing in multiple
forms is known as Polymorphism.
• Polymorphism is derived from 2 Greek words: word
"poly" means many and “morphs” means forms. So
polymorphism means MANY FORMS
Designed by:Vasudha
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.
Designed by:Vasudha
Designed by:Vasudha
Type of Polymorphism
• Polymorphism means more than one function with same name,
with different working.
• Polymorphism can be Compile Time and Run Time.
Designed by:Vasudha
Designed by:Vasudha
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;
1. Function Overloading
2. Operator Overloading.
Designed by:Vasudha
[Link] 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:
1. Different types of arguments or
2. Different number of arguments or
3. Different sequence or order of argument.
Designed by:Vasudha
Example:
1. These two have different number of parameters:
• sum(int num1, int num2)
• sum(int num1, int num2, int num3)
Designed by:Vasudha
WHY WE USE FUNCTION
OVERLOADING
• We use function overloading/method overloading
for the purpose of:
1. Compile time binding
2. Better Consistency
3. Better Readability
Designed by:Vasudha
Designed by:Vasudha
Designed by:Vasudha
#include <iostream.h> int main()
class show { show s;
{ void display ( ) [Link](); //function call with
{ int a = 3; no arguments
cout << a << endl; [Link](5); //function call with
} one integer argument
void display (int a ) [Link](2.3); //function call with
one floating argument
{ cout << a << endl; [Link](5,4.0f); //function call
} with one integer and one floating
void display (double a ) arguments
{ cout << a << endl; return 0;
} }
void display(int a, float b) //end of program
{ cout<< a << " , " << b <<
endl; Output
} • 3
}; • 5
• 2.3
• 5 , 4.0
Designed by:Vasudha
Designed by:Vasudha
Designed by:Vasudha
How to resolve overloading ambiguity
errors?
• If you don't want the implicit conversion sequence mapping to
throw you off, just provide functions and call them in such a
way so that the parameters are a exact match.
1. Call the function so that parameters are exact match to the
functions available.
• function(1.2f,2.2f);
• Since 1.2f and 2.2f are treated as float types they match
exactly to the float function version.
Designed by:Vasudha
[Link] Overloading
• Operator overloading is a compile-time polymorphism. It is an idea of
giving special meaning to an existing operator, without changing its
original meaning.
• We can overload the operator like (+, -, *, /, ==, <<, >>) etc., does when
applied to objects of your class.
Designed by:Vasudha
program to overload the
UNARY OPERATOR (++).
Designed by:Vasudha
#include <iostream.h>
class Test
{ public: int count;
public:
Test() // constructor called
{ count=5;
}
void operator ++( )
{ count = count + 5;
}
void Display()
{ cout<<"Count: "<<count;
}
};
int main()
{ Test t;
Designed by:Vasudha
How to overload the
BINARY OPERATOR .
• Overloading Binary Operator: In binary
operator overloading function, there should
be one argument to be passed.
• It is overloading of an operator operating on
two operands.
Designed by:Vasudha
a program to add two object values using (+)operator
#include<iostream.h>
class sum
{ public: int x;
sum(int i) //constructor called
{ x=i;
}
void operator+(sum a) //overload (+) operator function
{ int m = x + a.x;
cout<<"The result of the addition of two objects is : "<<m;
}
};
int main()
{
sum a1(5); x + a.x;
sum a2(4);
x;
a1+a2;
return 0; a2
a1
}
Designed by:Vasudha
a program to convert positive number into negative using
(-)operator
#include <iostream.h>
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;
}
Designed by:Vasudha
Run time Polymorphism
(Function Overriding)
Designed by:Vasudha
Virtual Function( implementation of
run time polymorphism)
• 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.
• It is used to tell the compiler to perform dynamic linkage or late binding
on the function.
• Late Binding: It happens with virtual functions where the exact function
to call is decided at runtime, depending on the actual object type. This
is slower because the program has to figure it out while running.
• Why we declare a function virtual? To let compiler know that the call
to this function needs to be resolved at runtime (also known as late
binding and dynamic linking) so that the object type is determined and
the correct version of the function is called. So, we create the pointer
to the base class that refers to all the derived objects.
Designed by:Vasudha
• IF WE NOT USE THE VIRTUAL KEYWORD: The 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.
Designed by:Vasudha
Designed by:Vasudha
#include <iostream.h>
class Number
{
public:
Virtual void display() // display() of the base class
{
cout<<“value is a number";
}
};
class Prime: public Number
{
public:
void display() // display() of the derive class
{
cout<<“value is a prime number";
}
};
int main( )
{
Number *n; // pointer object of base class
Prime p; //object of derived class
n = &p;
n-> display(); //Late Binding occurs
return 0;
}
Direct access
Indirect access
Pointer of base
*n by the pointer
class
Designed by:Vasudha
• 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 void eat() // eat() of the base class
class {
{ cout<<“Animal Eat food for energy";
cout<<“Animal Eat food for energy"; }
} };
}; class Cow: public Animal
class Cow: public Animal {
{ public:
public: void eat() // eat() of the derive class
void eat() // eat() of the derive class {
{ cout<<“Cow Eat grass...";
cout<<“Cow Eat grass..."; }
} };
}; int main(void)
int main(void) {
{ Animal *a; // pointer object of base class
Animal *a; // pointer object of base class Cow c; //object of derived class
Cow c; //object of derived class a = &c;
a = &c; a->eat(); //Late Binding occurs
a->eat(); //Late Binding occurs return 0;
return 0; }
}
Output: Animal Eat food for energy
Output: Cow Eat grass...
Designed by:Vasudha
FILE & EXCEPTION HANDLING
UNIT 4
Designed by:Vasudha
Files and Streams
• 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:
Designed by:Vasudha
Designed by:Vasudha
File Handling Operations
For achieving file handling in C++ we need follow following steps
1. Naming a file
2. Opening a file
3. Reading data from file
4. Writing data into file
5. Closing a file
Designed by:Vasudha
Defining and Opening a File
• The function open() can be used to open multiple files that use the same
stream object.
Designed by:Vasudha
Modes of Opening a file
• We need to tell the computer the purpose of opening our file.
e.g.-
• fstream filein("[Link]", ios::in);
• fstream str("[Link]", ios::in | ios::out);
These are the different modes in which we can open a file:
Designed by:Vasudha
#include <iostream.h>
#include <fstream.h>
int main()
{
fstream file;
[Link] ("[Link]", ios::out | ios::in );
[Link]();
return 0;
}
Designed by:Vasudha
Closing a File
• A file must be close after completion of all operation related to file. For
closing file we need close() function.
Designed by:Vasudha
Reading &Writing in a FILE
Designed by:Vasudha
Writing in a file…
Designed by:Vasudha
File is created in bin(folder)
Designed by:Vasudha
Demo file data
Designed by:Vasudha
Reading from a file
Designed by:Vasudha
Namespaces
• Namespaces in C++ is a declarative region that is used to organize too
many classes so that it can be easy to handle the application.
➢ Defining a Namespace:
• You define a namespace using the namespace keyword followed by the
namespace name and a block containing its members.
Advantage
• It maintains the normal flow of the application.
Designed by:Vasudha
try/catch example
Designed by:Vasudha
//program for negative number checking…..
#include <iostream.h>
using namespace std;
int main()
{
int x = -20;
try
{
if (x < 0)
{ throw x;
}
else
{ cout<<“value is positive”<<x;
}
}
catch (int x)
{
cout << "Exception Caught value of x is less than zero:"<<x;
}
return 0;
} Designed by:Vasudha
Designed by:Vasudha
//program for checking number divided by (ZERO)….
#include<iostream>
using namespace std;
int main()
{ int num1=10, num2=0; float num3;
try
{ if(num2==0)
{ throw(num2);
}
else
{ num3=num1/num2;
cout<<"outcome :"<<num3;
}
}
catch(int exc)
{ cout<<"division by zero is not possible. Please try again with
different value of variables";
}
} Designed by:Vasudha
Designed by:Vasudha
program for checking
“Array out of bound Exception”.
Designed by:Vasudha
#include<iostream>
using namespace std;
int main()
{
int arr[ ]={10,20,30,40,50};
int size=sizeof(arr) / sizeof(arr[0]);
int index;
cout<<"enter array index";
cin>>index;
try { if (index < 0 || index >=size)
{ throw "Error: Custom array index out of bounds!";
}
else
{ cout << "Element at index " << index << ": " << arr[index] << endl;
}
}
catch (const char* msg)
{ cout << msg << endl;
}
return 0; Designed by:Vasudha
}
Generic programming (Templates)
• A template is a powerful tool for creating generic classes or
functions.
• Key feature of templates :Avoid code duplication by allowing one
function or class to work with multiple data type.
• Templates can be defined using the keywords "template" and
"typename“.
Syntax: template <typename T>
➢ template keyword is used to define that the given entity is a
template.
➢ typename keyword is used to define template parameters which
are nothing but type.
Designed by:Vasudha
// Creating Template function to return maximum of two values:
#include<iostream>
using namespace std;
int main()
{
cout << "Max is:"<< Max<int>(8, 7) << endl;
cout << "Max is:" << Max<double>(6.5, 9.5) << endl;
cout << "Max is:" << Max<char>('v’, 'y') << endl;
}
return 0;
Designed by:Vasudha
#include<iostream>
using namespace std;
template<typename T>
T add(T a, T b) // template function create
{
T result=a+b;
return result;
}
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<<endl;
a= add(m,n);
cout<<"Addition of m and n is :"<<a<<endl;
return 0;
} Designed by:Vasudha
[Link] 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.
Designed by:Vasudha
• 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.
Designed by:Vasudha
#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<double>a2;
[Link](10,20);
[Link](5.5,4.5);
return 0;
}
Designed by:Vasudha
Designed by:Vasudha
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);
}
• Create another program and Include your header file with “#include” in your
program.
#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;
} Designed by:Vasudha