C++ Notes-1
C++ Notes-1
C++ Notes-1
Advantages of POP:
Easy to read the code since functions are used and also it is easy to
debug the code.
Disadvantages of POP:
1
Benefits of OOPL:
Advantages of OOPS:
Extendibility increases
Reusability increases
HISTORY OF C++ :
2
PROPERTIES OF OOPS
1) OBJECT
2) CLASS
3) ABSTRACTION
4) ENCAPSULATION
5) INHERITANCE
6) POLYMORPHISM
7) DYNAMIC BINDING
8) MESSAGE PASSING
OBJECT:
CLASS:
Class is a collection of objects
Class is a common name given to a group of objects
For example: IT is name of class. Each and every student present in
IT class is said to be a object.
In computer terminology class is called as collection of data and
functions.
Properties of object are represented by data (variables)
Behaviour of object is represented by functions of the class.
Example:
2.
objects class
Apple, mango,grapes,orange etc.,, fruit
Pink,blue,black,yellow etc.,, color
3
DATA ABSTRACTION:
DATA ENCAPSULATION:
INHERITANCE:
PLOYMORPHISM
4
DYNAMIC BINDING
MESSAGE PASSING:
Structure of C++:
1. Include files
2. Class declaration
3. Member functions
4. Definitions
5. Main function program
#include<iostream>
using namespace std;
main()
{
int a,b,c;
cout<<"enter 2 integers";
cin>>a>>b;
cout<<(a+b);
}
Note:
5
Iostream file : This directive causes the pre-processor to add the
contents of iostream to the program . it contains declaration for
identifiers. Cout and operator << and cin and operator >>.
6
INLINE FUNCTION:
Example:
#include<iostream>
using namespace std;
inline square(int h)
{
return h*h;
}
main()
{
cout<< square(5);
}
output: 25
In the above code when function call is made that is when square(5) is
executed by compiler the function definition will be replaces the
function call.
This happens when a function is preceded by the keyword “inline”
Advantage of inline function is that control of the program will be
with main() only.
Disadvantage is for each function call a separate copy of function
definition is created in memory.
Note:
Inline function may not work if it contains any loop
(s),switch,goto,static varibles.
Inline function cant be recurive.
member function defined inside the class are inline
7
REFERENCE VARIABLE
Example:
int x=10;
int &y=x;
cout<<x; //10
cout<<y; //10
REFERENCE TO A REFERNCE:
int x=10;
int &y=x;
int &m=y;
int &k=m;
cout<<x; //10
cout<<y; //10
cout<<m; //10
cout<<k //10
it is not possible to assign a different value for a reference
variable
8
UNARY SCOPE RESOLUTION OPERATOR (::)
Syntax : :: VariableName ;
Example:
#include<iostream>
using namespace std;
int m=10; //global variable
main()
{
int m=20;
cout<<m; //20
cout<< ::m; //10
}
9
OVERLOADING: It refers to the use of same task for different
purposes.
FUNCTION OVERLOADING
void area(int x)
{
cout<<”square area” <<x*x<<endl;
}
main()
{
area();
area(2,3);
area(2);
area(2.6f,3.6f);
}
10
ADVANTAGES OF FUNCTION OVERLOADING ARE:
NOTE:
Function overloading should be done with caution. That is we should
not overload function that are not related to each other.
Also if we are using classes and objects in function overloading then
all the functions should be present in the same class.
Functions of different classes cannot be overloaded.
TEMPLATES
Function Template:
If a program logic and operations are identical for each data type, this
may be performed more conveniently using function templates. All
function template definition begins with the keyword template
followed by list of formal type parameters to the function template
enclosed in <>. Every formal parameter is preceded by keyword class
or type name.
#include <iostream.h>
template <class T>
T max(T &a, T &b)
{
if(a>b)
return a;
else
return b;
}
11
main()
{
cout << max(10, 20);
cout << max(‘v’,’m’);
cout << max(3.5f,4.5f);
}
After seeing a function template compiler remembers it for future use.
Compiler will not generate any code using function template since it
don’t know that kind of data it is going to handle.
When a function call is made depending on the type of values passed
compiler substitutes that data type in place of ‘T’ in the function
template.
template<class t>
class bubble
{
t a[20];
public:
void get(int);
void sort(int);
void display(int);
};
template<class t>
void bubble<t>::get(int n)
{
cout<<"enter elements";
for(int i=0;i<n;i++)
cin>>a[i];
}
template<class t>
void bubble<t>::display(int n)
{
cout<<"sorted array is";
for(iint i=0;i<n;i++)
cout<<a[i];
}
12
template<class t>
void bubble<t>::sort(int n)
{
t temp;
for(int i=0; i<n; i++)
for(int j=0;j<n-1;j++)
if(a[j] > a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
main()
{
bubble<int> b1;
cout<<"integer sorting";
b1.get(5);
b1.sort(5);
b1.display(5);
bubble<char> b2;
cout<<"character sorting";
b2.get(5);
b2.sort(5);
b2.display(5);
}
13
CLASSES AND DATA ABSTRACTION:
Object_name.function();
14
Program to find average of 3 numbers using the concept of class,
object and member function
#include<iostream>
using namespace std;
class demo
{
private:
int x,y,z;
float k;
public:
void input(int,int,int);
void output();
void average();
};
void demo::output()
{
cout<<k;
}
void demo::average()
{
k=(x+y+z)/3;
}
main()
{
demo d;
d.input(10,20,30);
d.average();
d.output();
}
A function can be defined either inside or outside the class.
If it is defined outside then:
It should be written along with its class name and ::
15
Scope Rules:
Note:
If a member function defines a variable with the same name as a
variable with the class scope, the class scope variable is hidden by
function scope variable in the function scope such variable can be
accessed by class name::variable name
Example: (refer class notes)
CONSTRUCTOR
PROPERTIES OF CONSTRUCTOR:
Name of the constructor function is same as class name
It has no return type not even void
There is no private constructor i.e., Constructor must be public.
Constructor may or may not have parameters.
Constructor cannot return a value.
Constructor cannot be friend function to any other class.
16
Syntax of constructor is:
class_name()
{
….
….}
1. Default constructor
When a class is created then compiler automatically allocates a
constructor called as default constructor. (A class can contain only
one default constructor i.e default constructor cannot be
overloaded)
2. Non-parameterized constructor
Constructor with no parameters
3. Parameterized constructor
Constructor with parameters. (We can pass arguments to
constructor while creating the object within the parenthesis beside
object)
4. Copy constructor
Passing object as an argument.
That is initializing object of one class with other object of same
class is called copy initialization.
Such a constructor is called as copy constructor
17
Program for Constructor Overloading
#include<iostream>
using namespace std;
class abc
{
private: int a,b;
public:
abc( )
{
cout<<”default constructor \n”;
a=10;
b=20;
}
abc(abc &i)
{
cout<<”copy constructor \n”;
a=i.a;
b=i.b;
}
void diaplay()
{
cout<<”a”<<a<<”b”<<b<<endl;
}
}
main()
{
abc ob1;
18
abc ob2(30,40);
abc ob3(ob2);
ob1.display();
ob2.display();
ob3.display();
}
Output:
a 10 b 10
a 30 b 40
a 30 b 40
DESTRUCTOR
Syntax : ~class_name()
{
}
Note:
The destructor function also has the same name as a class but
preceded by tilde(~) character.
The name of the destructor for a class is a tilde followed by the
class name.
Class destructor is called when an object is destroyed.
A destructor freezes the memory occupied by the object so that it
can be reused to hold new object.
Destructor is declared in the public section of a class
Destructor receives no parameters and no return value.
Destructor cannot be overloaded.
19
Default constructor cannot be overloaded.
#include<iostream>
using namespace std;
class abc
{
public:
abc()
{
cout<<”constructor is called\n”;
}
~abc()
{
cout<<”destructor is called\n”;
}
};
main( )
{
abc ob1;
}
Output:
Constructor is called
Destructor is called
20
Program to demonstrate destructor
Ex:2
#include<iostream>
using namespace std;
int c=0;
class abc
{
public:
abc()
{
c++;
cout<<" object"<<c<<”is created\n”;
}
~abc()
{
cout<<"object"<<c<<”is destroyed\n”;
c--;
}
};
main()
{
cout<<" In main";
abc a1,a2;
{
cout<<"block-1";
abc a3;
}
}
Output:
In main
Object 1 is created
Object 2 is created
Object 3 is created
Object 3 is destroyed
Object 2 is destroyed
Object 1 is destroyed
21
FRIEND FUNCTION
“friend” is a keyword.
Friend function is used to access the private data of the class.
Friend function takes object of a class as an argument
Friend function cannot refer members of class directly. It uses the
object to refer them
Friend function cannot be called using object of class, it should be
called directly.
Normal values cannot be passed as arguments in friend function.
A friend function of a class is defined outside the class scope and yet
has right to access private members of the class.
A function or entire class may be declared to be a friend of another
class.
To declare a function as a friend of a class receive the function
prototype in class declaration with friend keyword.
Syntax:
Characteristics:
It is not in the scope of the class to which it has been declared as friend.
It cannot be called using the object of the class.
It can be called like a normal function without the help of any object.
It can be declared either in public or private part of the class.
It has an object as an argument.
22
Program to demonstrate friend function
#include<iostream>
using namespace std;
class sample
{
private:
int m1,m2,m3;
public:
void getmarks();
friend void total(sample );
};
Int total(sample s)
{
return (s.nm1+s.m2+s.m3);
}
main()
{
sample e;
e.getmarks();
cout<<”total marks “<<total(e);
}
Output:
enter m1 m2 m3 marks
90 80 70
total marks 240
23
“this” POINTER
#include<iostream>
using namespace std;
class abc
{
int x;
public:
abc()
{
x=10;
}
void function(int x)
{
cout<< x;//20
cout<< this->x;//10
}
};
main()
{
abc a1;
a1.function(20);
}
Output: 20
10
24
Application of ‘this’ pointer:
To return the object to which it points to.
To compare two or more objects inside a member function and
return the invoking object as a result.
#include<iostream>
using namespace std;
class max
{
int a;
public:
void get()
{
cout<<"enter a";
cin>>a;
}
void compare(max m)
{
if(this->a > m.a)
cout<<"max no. is"<<this->a;
else
cout<<"max no. is"<<x.a;
}
};
main()
{
max p,q;
p.get();
q.get();
p.compare(q);
}
Out put:
Enter a 10
25
Enter a 20
Max no. is 20
Dynamic Memory Allocation:
C++ provides two dynamic allocation operators: new and delete. These
operators are used to allocate and free memory at run time.
C++ also supports dynamic memory allocation functions, called malloc() and
free().
.
The new operator allocates memory and returns a pointer to the start of it.
The delete operator frees memory previously allocated using new.
delete variable;
main()
{
int *p = new int; // allocates memory( space ) for an int
*p = 100;
cout << "At " << p << " ";
cout << "is the value " << *p << "\n";
delete p; // deallocates memory for variable p
}
You can allocate arrays using new by using this general form:
delete [ ] variable;
26
In C language we are provided with dynamic memory allocation functions
like malloc(),calloc(),free().
Syntax:
Data type *variable = (datatype *) malloc( sizeof(datatype) );
For Arrays:
Calloc(): allocates memory dynamically at run time
Syntax:
Data type *variable = (datatype *) calloc(n, sizeof(datatype) );
Where: n is size of array.
Ex: int *p = (int *)calloc( 10,sizeof(int) ); // which allocates 20 bytes for the
variable p at run time.
For De-Allocation:
free(): Deallocate memory at run time.
Syntax:
free(variable name);
Ex: free(p);
27
DYNAMIC MEMORY ALLOCATION
int x[10];
28
PROGRAM FOR DYNAMIC MEMORY ALLOCATION
#include<iostream>
using namespace std;
main()
{
int size,i;
cout<<"enter array size";
cin>>size;
cout"<<"enter elements";
for(i=0;i<size;i++)
cin>>p[i];
cout<<"elements are";
for(i=0;i<size;i++)
cout<<p[i];
delete [ ]p;
}
29
CONSTANT OBJECTS AND CONSTANT MEMBER FUNCTIONS
If we don’t want to modify value of some object then we can use the
keyword “const”.
If a member function does not modify any data member in the class
then we can declare it as “const” member function.
A “const” object can call only constant member function.
A non-const object can call both const member function and non-
const member function.
demo(int p,int q)
{
x=p;
y=q;
}
void display()
{
cout<<"hello";
30
}
};
main()
{
demo d1;
const demo d2(20,40);
d1.show();
d2.show();
d1.display();
d2.display();// error
}
31
STATIC VARIABLES AND STATIC MEMBER FUNCTIONS
No matter how many objects of a class are created, only one copy of a
static data member exists. Thus, all objects of that class use that
same variable.
All static variables are initialized to zero before the first object is
created.
When you declare a static data member within a class, you are not
defining it. (That is, you are not allocating storage for it.)
#include<iostream>
using namespace std;
class A
{
public:
static int count;
A()
{
count++;
}
};
32
int A::count;
main()
{
A a1,a2,a3;
cout<<"objects created "<<a1.count;
A a4,a5;
cout<<"objects created "<<A::count;
}
output:
objects created 3
objects created 5
#include<iostream>
using namespace std;
class A
{
public:
static int x,y;
A()
{
x++; y=5;
}
void static put();
33
};
void A::put()
{
cout<<x;
cout<<y;
}
int A::x;
main()
{
A p,q,r;
p.put();
A s,t;
A::put();
}
Output: 3 5
34
OPERATOR OVERLOADING
Unary operators are operators that act upon only single operand.
Example: ++, - -, -
Binary operators are operators acting upon two operands
Example: +, /.%,<,> etc.,
Operators like new,delete,(,),[,] etc., are special operators.
>> and << are extraction and insertion operators.
35
PROGRAM FOR UNARY OPERATOR OVERLOADING
#include<iostream>
using namespace std;
class unary
{
int a,b;
public:
void get();
void display();
void operator -();
};
void unary::get()
{
cout<<"enter the values of a and b"<<"\n";
cin>>a>>b;
}
void unary:: display()
{
cout<<"a= "<<a<<" ,b= "<<b<<endl;
}
36
PROGRAM FOR CREATION OF COMPLEX CLASS WITH
OPERATOR OVERLOADING (binary operator overloading)
#include<iostream>
using namespace std;
class complex
{
float x,y;
public:
complex()
{
x=0;
y=0;
}
void display()
{
cout<<x<<" "<<y<<endl;
}
};
37
main()
{
complex c1(2.6,3.6),c2(4.6,5.6),c3;
c3=c1+c2;
c1. display();
c2.display();
c3.display();
}
we can not change the basic meaning of an operator i.e we can not use +
for subtraction
38
Operator overloading can be done using friend function also
39