0% found this document useful (0 votes)
68 views61 pages

C

C++ is an expanded and improved version of C programming that is object-oriented. It was invented in 1979 at Bell Labs by Bjarne Stroustrup. C++ supports features like classes, inheritance, polymorphism, and namespaces that allow for object-oriented programming. It runs on many platforms like Linux, Windows, and Mac. Some key differences between C and C++ include C++ supporting object-oriented concepts like classes, inheritance, and function overloading.

Uploaded by

Ramanan M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views61 pages

C

C++ is an expanded and improved version of C programming that is object-oriented. It was invented in 1979 at Bell Labs by Bjarne Stroustrup. C++ supports features like classes, inheritance, polymorphism, and namespaces that allow for object-oriented programming. It runs on many platforms like Linux, Windows, and Mac. Some key differences between C and C++ include C++ supporting object-oriented concepts like classes, inheritance, and function overloading.

Uploaded by

Ramanan M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

c++ is an expanded version of c programming

-> middle level


-> father of c++ was Bjarne stroustrup
-> it was inveted in the year 1979 in bell laboratries in murray
-> runs on a variety of different platform(linux,window,mac)

features:
======
middle leve
c++ is an object orinted programming language.
fast & robust
simple

why to go for c++?


1.it was invented for major programming complexity( increasing complexity).
2.for better understanding of oops concepts
3. comparing to c c++ is more efficient

major features of c++ are(oops):


===================
1. abstraction : hiding the non essential details & showing the required
essential details eg: television,project abstract, human being
2.encapsulation (private): binding the data & function together protecting it
from the outside interfernce and data corruption.
bank details,
3.inheritance : deriving the properties of the parent class into the child class
and the child class has its own extra features is known as inheritance parent
class: super class, child class : sub class eg : parent child relation

4.polymorphism: poly means many & morphism means forms (many forms) this process
performs different operation on a differnt scenario
categories
==========
1.compile time poly (static polymorphism)(early binding)
===============
a.function overloading
b.operator overloading

2. runtime poly(dynamic polymorphism)(late binding)


===================================
1.function overridding
2.virtual

============

Application of c++
===============
1.operating system
2.database managements
3.compiler design or interpretor
4.web server
5.cloud based application
6.linux device driver
7.search engines
8.embedded system.

Access specifiers
=================
1.public
2. private
3. protected
4.default
difference s between c & c++
=======================
C
C++
1.procedure oriented programming language 1.object
oriented programming language (PO)
2. #include<stdio.h>
2.#include<iostream>
3. main()
3.int main()-> return type always expects to be int
4.printf(), scanf()
4. cin cout are object used for printing & reading data
5. format specifier required
5. format specifier not required (variable name can access values)
6.no access specifier
6. private public protected
7. the deafult access specifier is public
7.default access spec is private
8.it doesnot supports E,A,I,P
8.supports E,A,I,P
9.function overloading not supported 9.
func overloading is supported
10.namespace is not supported
10. namesapce support
11.funoverriding not supported
11. it supports func overridding
12. char datatype is 1 bytes
12 char datatype in c++ is 4 bytes
13.empty struct zero byte
13. size of empty structure is 1 byte
14.static keyword is not allowed in structure 14. static
keyword is allowed
15.functions cannot be wrriten inside the structure 15. we can write
functions inside
16. usually declare a structure in c we use struct keyword 16. we use class
keyword to describe a structure

we need to include the namesapce that is std in every program because the input
& output object are decleared inside the namespace std.

endl is an object in c++ which acts just as the \n newline character in our c
program we can also make use of \n also becuase some small features of c
programming supports in c++. endl is an object its declaration is also inside
the namespace std and definition is inside iostream

#include<iostream>
using namespace std;
int main()//mandatory to have int
{
cout<<"hello"<<endl;
cout<<"world\n";
int a=10;
cout<<"a is ="<<a<<endl;
cout<<"enter the value for a\n";
cin>>a;
cout<<"a is ="<<a<<endl;

}
//std::cout
/*<< ->insertion operator
>> -> extraction operator*/

Namespaces in c++
==============
int main()
{
int a=10;
double a=9.9;
cout<<a;
} this will generate an error redeclaration but this can be over come with the
namespce

Namespace is used to avoid the name collison . we can reuse the variable and the
function name with the helep of namespaces

there are two ways to avoid name collision


================================
1. :: (scope resolution operator)
namespace _keyword namespace _name
{
// code
}

namespace_name :: code

namespace first
{
int a=90;
void func()
{
cout<<"this is first namespace\n";
}
}
namespace sec
{
double a=9.7;
void func()
{
cout<<"this is a sec namespace\n";
}
}
int main()
{
cout<<first::a<<endl;
first :: func();

cout<<sec::a<<endl;
sec: func();

2. using keyword
=============

#include<iostream>
using namespace std;
namespace first
{
int a=90;
void func()
{
cout<<"this is first namespace\n";
}
}
namespace sec
{
double a=9.7;
void func()
{
cout<<"this is a sec namespace\n";
}
}

int main()
{
// {
// using namespace first;
cout<<a<<endl;
func();
// }
// {
//using namespace sec;
cout<<a<<endl;
func();
// }

class: it is a coimbination of data members & member function. and a class is


declared with the keyword "class".
complete structure which is enclosed into a scope & terminated by a ;
syn
===
class_keyword class_name
{
data member;
member function
{
//code
}
};
int main()
{
class_name object_name;
}
this is a class template the class will work only when we declare an object to
the class.
for one class we can declare n objects every object acts or allocates memory
separately

object: it is a variable of a class or we can say its an instance of the class.


characteristics of object
==================
1.behaviour
2.identity

example
=======
#include<iostream>
using namespace std;
class number
{
int a=78;
int b=12;//data members
public: void add()//mem func
{
cout<<"the sum is "<<a+b<<endl;
}
void multiply()
{
cout<<"the product is "<<a*b<<endl;
}
};

int main()
{
number obj;
obj.add();
obj.multiply();
}

example:
========
class test
{
int data;
double val;
public: void func1()
{
data=67;
cout<<data<<endl;
}
void func2()
{
val=89.577;
cout<<val<<endl;
}
};
int main()
{
test t1;
t1.func1();
t1.func2();
test t2;
t2.func1();
t2.func2();

#include<iostream>
using namespace std;
class test
{
int a,b;
public : void set( int x, int y)
{
a=x;
b=y;
}
int sum()
{
return a+b;
}
};
int main()
{
test n,n1;
n.set(3,6);
cout<<"the sum is"<<" "<<n.sum()<<endl;
n1.set(5,8);
cout<<"the sum is"<<" "<<n1.sum()<<endl;
}

reference operator "&"


=================
referencing different varainble to the same memory or the varaible which are
already existing:

syn:
===
type &reference_name =variable//value error

1. a refernce var should always be intialized with a already existing var.


2. a reference variable cannot be refered with a constant literal
3.it can only refere to a var

int a=10;
int &b=a;
int &x=b;
b++;

call by reference
=============
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
int main()
{
int a=10,b=90;
swap(a,b);
cout<<a << b <<endl;
}

default arguments
===============
#include<iostream>
using namespace std;
int sum(int h,int g=0,int c=0,int d=0);
int main()
{
cout<<sum(78)<<endl;
cout<<sum(23,56,5)<<endl;

cout<<sum(23,56,78,4)<<endl;
}
int sum(int x,int y,int z, int w)
{
return x+y+z+w;
}
Default arguments:
=================
values provided to fdunction decalaration that is automatically assigned by the
compiler if the caller of the function doesnot provide any value while calling
the function.
-> default arguments should be always provide from RHS to LHS
default arguments should be provided in func dec, or prototype

Inline function:
===========
if a function is declared as inline then at the time if compilation the body of
the function get expanbded instead of performing overhaed of the function.
-> the function is expanded at the point at which it is called
-> it basically works for smaller function & not for larger function

difference between macro & inline


==========================
both dont follow function overhead
-> macro are substituted at preprocessing & inline is at compliation
-> in macro guaranteed text substitution but in inline there is no gauranrtedd
text substitution since it works for only small functions.
-> macros dont evaluate arguments only substitutes but inline function evaluate
and substitute

#include<iostream>
using namespace std;
#define square(x) (x)*(x)
/*inline int square(int x)
{
return x*x;
}*/
int main()
{
int x = 5;
cout<<square(x+2)<<endl;
}
//(x + 2) * (x + 2)//49
//x + 2*x +2

compiler timr poly


==============
Function overloading
================

->multiple fun ctions having the same name


-> calls to an overloaded fuction can be resolved at the compile time by
follwing the signatures
1.no of args
2. type of args
3. order of args

function return type has no role in function overloading.


"single interface multiple implementation"

name mangling
=============
when we provide function overloading to a program internally the compiler will
first check the siganture later it will give new names to the function that it
wants to be recognised.

#include<iostream>
using namespace std;
int fun(double x,int y)
{
// x=9;
cout<<x +y<<endl;;
}
int fun(int y,double x)
{
// y=7,x=5;
cout<<y*x<<endl;;
}
int main()
{
fun(9.8,6);
fun(7,5.0);
}

#include<iostream>
using namespace std;
double area(int radius)
{
return 3.14 * radius * radius;
}
int area(int length, int breadth)
{
return length * breadth;
}
int main()
{
cout<<area(5)<<endl;
cout<<area(5,3)<<endl;
}

constructors:
==========
->it is a special member function of the class
-> they are used to set the values of the data members of the class.
->the name of the constructor will be same as the class name
->the constructor donot have a return type.
-> constructors are automatically invoked when we create the object of the
class.

class test
{
int a,b;
public: test()
{
a=10;b=89;
}
void display()
{
cout<<" value of a is "<<a<<endl;
cout<<"value of b is "<<b<<endl;
}
};
int main()
{
test obj;
obj.display();
}
types of constructors:
=================
1.default constructor
2.argumented (parameterised constructor)
3.copy constructor

default constructor: a construtors with ni arguments and invoked automatically


when the object is created is known as a default constructor.

#include<iostream>
using namespace std;
class test
{
int a,b;
public: test()//default constructor
{
a=10;b=89;
cout<<"constructor invoked\n";
}
void display()
{
cout<<" value of a is "<<a<<endl;
cout<<"value of b is "<<b<<endl;
}
};
int main()
{
test obj,obj1;
obj.display();
//test obj1;
obj1.display();
}

Parameterized constructor
=====================
constructor with arguments is known as an argumented or paramerterized const

#include<iostream>
using namespace std;
class test
{
int a,b;
public: test(int x,int y)//default constructor
{
a=x;b=y;
cout<<"constructor invoked\n";
}
void display()
{
cout<<" value of a is "<<a<<endl;
cout<<"value of b is "<<b<<endl;
}
};
int main()
{
test obj;
obj.display();

}
#include<iostream>
using namespace std;
class test
{
int a,b;
public:
test()
{
cout<<"this is default\n";
}
test(int x,int y)//arg constructor
{
a=x;b=y;
cout<<"constructor invoked\n";
}
void display()
{
cout<<" value of a is "<<a<<endl;
cout<<"value of b is "<<b<<endl;
}
};
int main()
{
test obj(6,7);
obj.display();
test obj1(8,4);
obj1.display();
test t;
t.display();

we can also overload our constructors by follwing the same signatures that of
the function oveloadiong
1.no of argumnts
2. type of arguments
3.order of arguments

#include<iostream>
using namespace std;
class test
{
int a; double b;
public:
test()
{
cout<<"this is default\n";
}
test(int x,int y)//arg constructor
{
a=x;b=y;
cout<<"constructor invoked\n";
}
test(int x,double y)//arg constructor
{
a=x;b=y;
cout<<"constructor invoked\n";
}
void display()
{
cout<<" value of a is "<<a<<endl;
cout<<"value of b is "<<b<<endl;
}
};
int main()
{
test obj(6,7);
obj.display();
test obj1(8,4.5);
obj1.display();
test t;
t.display();

we can also provide constructors with default value just like our functions and
it acts as both default & argumented constructor

#include<iostream>
using namespace std;
class test
{
int a,b;
public : test(int x=0,int y=0)//both arg & default const
{
a=x;
b=y;
}
void show()
{
cout<<a<<"\n"<<b<<endl;
}
};
int main()
{
test t(1,3);
test t1(5);
t.show();
t1.show();
test t3;
t3.show();
}
copy constructor
=============
copy constructorv is called when a new object is created from an already
existing object

syn
====
class name new object=already existing obj ;

2.class name new object(already existing obj) ;

there are two types of copy constructor


1.shallow copy constructor: whenever the copy constructor is invoked it will
search for an userdefiend copy constructor if ther is no userdefined copy
constructor present in our class then the compiler would have already provided a
default copy constructor hence it will perform shallow copy where all the object
created from the existing objects will allocate in the sme memory so any changes
done to the datamembers & mem functions, then all the object will reflect the
changes done on one object.

-> usually shallow copy happen when no user defined copy constructor is
available
#include<iostream>
using namespace std;
class exam
{
int a,b;
public : exam(int s,int q)
{
a=s;b=q;
}
void display()
{
cout<<a<< " "<<b<<endl;
}
};
int main()
{
exam obj(10,20);
obj.display();
exam obj1(obj);//shallow copy
obj1.display();
exam obj2=obj1;
obj2.display();
}

2.deep copy constructor


==================
when there is an user defined copy constructor present in our class then the
deep copy will be performed.
if we are creating an obj from the already existing object and at the time of
invocation of the copy constructor it will search for a user def copy
constructor if it is present then it will consider as deeep copy where memory
allocated to every object is separate

class_name (const classname & old_obj)


{
code
}

#include<iostream>
using namespace std;
class exam
{
int a,b;
public : exam(int s,int q)
{
a=s;b=q;
}
exam (exam &e)
{
a=e.a;
b=e.b;
}
void display()
{
cout<<a<< " "<<b<<endl;
}
};
int main()
{
exam obj(10,20);
obj.display();
exam obj1(obj);//deep copy
obj1.display();
exam obj2=obj1;
obj2.display();
}
difference between deep copy & shallow copy
==================================
1.deep copy requires userdefined copy constructor shallow copy dont require
2.deep copy there will be no memory sharing shallow copy shares the memory among
the objects
3.deep copy allocate different memory but data will be referenced... but in
shallow copy since there is memory sharing all data with all object will be
same.

writing the function definition outside the class:


====================================
#include<iostream>
using namespace std;
class hello
{
int a,b;//even if id private or public it is harmful to
//access data members of the class outside class by using :: operator
public:void set_value(int x,int y)
{
a=x;b=y;
}
void show();//mem function
};
void hello::show()
{
cout<<a<<" "<<b;
}
int main()
{
hello h;
cout<<hello::a;//provide compile time error
h.set_value(5,7);
h.show();
}

Dynamic memory allocation


======================
malloc()
calloc() both are supported in c++ also

the features of DMA in c++


=====================
there are two opeartors
1.new (operator) -> allocate the memory
2.delete (operator)-> free or deallocating the memory

syn
===
allocating mem
============
datatype *pointer_var= new datatype;

freeing mem
========
delete *pointer_var;

#include<iostream>
using namespace std;
int main()
{
int *n= new int;
cout<<*n;
}

#include<iostream>
using namespace std;
int main()
{
int *n= new int(10);//valid intial
*n=20;//valid intial
cout<<*n;
delete n;
}

character DMA
============
int main()
{
char *cptr =new char('a')
cout<< *cptr;
delete cptr;
}

DMA for an integer array


===================

#include<iostream>
using namespace std;
int main()
{
int *ptr=new int[5];
cout<<"enter the values for my array\n";
int i;
for(i=0;i<5;i++)
cin>>ptr+i
cout<<"the array elements are\n";
for(i=0;i<5;i++)
cout<<*(ptr+i);
delete ptr;
}

DMA for classes & objects


========================
#include<iostream>
using namespace std;
class Box
{
public:Box()
{
cout<<"this is my constructor\n";
}
};
int main()
{
Box b;//static object
Box *b1= new Box;//dynamic object
delete b1;
}

#include<iostream>
using namespace std;
class Box
{
public:Box()
{
cout<<"this is my constructor\n";
}
};
int main()
{
Box b;//static object
Box *b1= new Box;//dynamic object
Box *myarray=new Box[5];//
delete b1;
delete []myarray;
}

#include<iostream>
using namespace std;
class Box
{
public:Box()
{
cout<<"this is my constructor\n";
}
};
int main()
{
Box b[3];//static object//temporay allocation
Box *b1= new Box;//dynamic object
Box *myarray=new Box[5];//dynamic objects in array
delete b1;
delete []myarray;
}

Destructors:
=========
->it is a special member function of the class
-> they are used to destroy the objects
->the name of the destructor will be same as the class name
->the destructor donot have a return type.
-> destructors are automatically invoked when the object of the class are going
out of the scope or if they are destroyed
-> if there is no destructor also the objects that are created are destryed
becoz the compiler gives a default destructor to the class.
-> destructors are invoked in the reverse order..
syn
===
~class_name()
{
}

#include<iostream>
using namespace std;
class test
{
public:test()
{
cout<<"constructor\n";
}
~test()
{
cout<<"destructor\n";
}
};
int main()
{
test t,t1,t2;
}

#include<iostream>
using namespace std;
class Box
{
public:Box()
{
cout<<"this is my constructor\n";
}
~Box()
{
cout<<"destructor\n";
};
int main()
{
Box b[3];//static object//temporay allocation
Box *b1= new Box;//dynamic object
Box *myarray=new Box[5];//dynamic objects in array
delete b1;
delete []myarray;
}

#include<iostream>
#include<cstring>//
using namespace std;

class String
{

char *s;
int size;
public:
String(const char *str = NULL); //constructor declared in class
~String()
{
delete [] s;
}
void print()
{
cout << s << endl;
}
void change( char *); // Function to change
};

String::String(const char *str)


{
size = strlen(str);//6
s = new char[size+1];
strcpy(s, str);
}

void String::change(const char *str)


{
delete [] s;
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}

int main()
{
String str1("cranes");
String str2 = str1;

str1.print(); //cranes
str2.print();//cranes

str2.change("cranesvarsity");

str1.print(); //cranes varsity


str2.print(); //cranes varsity
return 0;
}

#include<iostream>
#include<cstring>
using namespace std;
class String
{
private:
char *s;
int size;
public:
String(const char *str = NULL); // constructor
~String()
{
delete [] s;
}// destructor
String(const String&); // copy constructor
void print()
{
cout << s << endl;
} // Function to print string
void change(const char *); // Function to change
};
String::String(const char *str)//arg const
{
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}
void String::change(const char *str)//function
{
delete [] s;
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}
String::String(const String& old_str)
{
size = old_str.size;
s = new char[size+1];
strcpy(s, old_str.s);
}//user defined copy constructor
int main()
{
String str1("cranes");
String str2 = str1;
str1.print(); // what is printed ?//cranes
str2.print();//cranes
str2.change("cranesvarsity");
str1.print(); // what is printed now ?//cranes
str2.print();//cranesvarsity
return 0;
}

usually the compiler will give some functionalities to the class if there is no
user defined ones
1.defualt constructor
2.destructor
3.copy constructor
4.this

This pointer:
=========
internally the compiler will give a this pointer. this pointer hold the address
of the current object with which it is invoked
example
======
#include<iostream>
using namespace std;
class test
{
int a, b;
public : test( int a, int b)
{
this->a=a;
this->b=b;
}
void display()
{
cout<<a<< " "<<b<<endl;
}
};
int main()
{
test t(4,6);
t.display();
}
#include<iostream>
using namespace std;
class test
{
int a, b;
public : void set( int a, int b)
{
this->a=a;
this->b=b;
}
void display()
{
cout<<a<< " "<<b<<endl;
}
};
int main()
{
test t;
t.set(3,4);
t.display();
}

static keyword:
==============
1.static variable inside the function
2.static class obj
3.static member variable in the class
4. static member function inside the class

1.static variable inside the function


1.#include<iostream>
using namespace std;
int fun();
int main()
{
cout<<fun()<<endl;//1//1
cout<<fun()<<endl;//2//1
cout<<fun()<<endl;//3//1
}
int fun()
{
int count=0;
count++;
return count;
}

3.static member variable in the class


============================
#include<iostream>
using namespace std;
class test
{
static int a;

public:test()
{

cout<<"hello constructor\n";
}
void print()
{
cout<<a<<endl;
}
};
int test::a=76;
int main()
{
test t;
t.print();
}

1.we cannot initialised a static dat mem of the class within a class
2.static data members can be access within static function & normal fuctions but
non static dat members cannot be accessed inside the static function of the
class
3.static dat member are explicitly intialized outside the class with the scope
resolution operators

4. static member function inside the class


=================================
#include<iostream>
using namespace std;
class test
{
static int a;

public:test()
{

cout<<"hello constructor\n";
}
static void print()
{
cout<<a<<endl;
}
};
int test::a=76;
int main()
{
test t;
t.print();
}
#include<iostream>
using namespace std;
class test
{
static int a;
int x;//non static

public:test()
{

x=46;
cout<<"hello constructor\n";
}
static void print()
{
cout<<x<<endl;//cannot access inside the static function
cout<<a<<endl;//only static variables can be accessed in the
class
}
};
int test::a=76;
int main()
{
test t;
t.print();
}

Acessing the ststic function of the class with class name & scope resolution
operator

#include<iostream>
using namespace std;
class test
{
static int a;
int x;//non static

public:test()
{

x=46;
cout<<"hello constructor\n";
}
static void print()
{
//cout<<x<<endl;//cannot access inside the static function
cout<<a<<endl;//only static variables can be accessed in the
class
}
};
int test::a=76;
int main()
{
test t;
t.print();
test::print();//we can access the static function is this form also
}

2.static class obj


==============
#include<iostream>
using namespace std;
class test
{
int i;
public : test()
{
i=10;
cout<<"constructor\n";
}
~test()
{
cout<<"destructor\n";
}
};
void fun()
{
test t;
}
int main()
{
int a=0;
if(a==0)
fun();
cout<<"end\n";
}//const,destr,end

if the static object is created within any scope then the object is alive
throught the program ... if it is a normal object inwhich scope it is decalared
it will be alive only within that scope not throught the program

#include<iostream>
using namespace std;
class test
{
int i;
public : test()
{
i=10;
cout<<"constructor\n";
}
~test()
{
cout<<"destructor\n";
}
};
void fun()
{
static test t;
}
int main()
{
int a=0;
if(a==0)
fun();
cout<<"end\n";
}//const,end, destr

#include<iostream>
using namespace std;
class st
{
int code;
static int count;
public:
st()
{
cout<<"construcotr\n";
code=++count;
}
void showcode()
{
cout<<"code-->"<<code<<endl;
}
static void showcount()
{
cout<<"count-->"<<count<<endl;
}

};
int st::count;
int main()
{
st o1,o2,o3;
o1.showcode();
o1.showcount();
o2.showcode();
o2.showcount();
o3.showcode();
o3.showcount();
}

Friend function
============
Normally when we write only the declaration of the function in the class and try
to define it outside the class we where using the class name & the :: scope
resolution operator but for the same thing if we declare it as a friend then we
dont have to use the class name & the :: Scope resolution operator also.

example:
#include<iostream>
using namespce std;
class test
{
int a,b;
public: test(int a,int b)
{
this->a=a;
this->b=b;
}
friend void display(test);
};
void display(test s)
{
cout<<s.a<<" "<<s.b<<endl;
}
int main()
{
test t(2,4);
display(t);
}

#include<iostream>
using namespace std;
class frd
{
int a,b,c;
public : frd()
{
a=9,b=5,c=2;
}
friend int mean(frd);
};
int mean(frd f)
{
int res =(f.a +f.b+ f.c)/3;
return res;
}
int main()
{
frd obj;
cout<<mean(obj);
}

#include<iostream>
using namespace std;
class A
{
int a,b;
public:
A()
{
a=10,b=20;
}
~A()
{
cout<<"destructor"<<endl;
}
friend void multi( A);
};
void multi(A x)
{
cout<<"a*b-->"<<x.a * x.b<<endl;
}
int main()
{
A o;
multi(o);
}

if we dont create an object in main then we dont have to pass argument of type
class in the friend fuction but if the object itself is created in the friend
class then the obj is alive only withibn that scope & we don not have to pass an
argumnet in the friend function

#include<iostream>
using namespace std;
class A
{
int a,b;
public:
A()
{
a=10,b=20;
}
~A()
{
cout<<"destructor"<<endl;
}
void display()
{
cout<<a<<" "<<b<<endl;
}
friend void multi( );
};
void multi()
{
A o;
o.display();
}
int main()
{

multi();
}

friend class:
==========
having a friendship from one class to another is known as a friend class

this is acting as pass by reference in friend class


#include<iostream>
using namespace std;
class A
{
int a;
public:
A()
{
a=12;
}
void shw()
{
cout<<"in class a:a--> "<<a<<endl;//12

}
friend class B;//class being a friend
};
class B
{
int b;
public:
void show(A& x)
{
x.a=24;
cout<<"A::a-->"<<x.a<<endl;//24
}

};
int main()
{
A a;
B b;
b.show(a);
a.shw();
}

this is acting as a pass by value in the friend class


======================================
#include<iostream>
using namespace std;
class A
{
int a;
public:
A()
{
a=12;
}
void shw()
{
cout<<"in class a:a--> "<<a<<endl;//12

}
friend class B;//class being a friend
};
class B
{
int b;
public:
void show(A x)
{
x.a=24;
cout<<"A::a-->"<<x.a<<endl;//24
}

};
int main()
{
A a;
B b;
b.show(a);
a.shw();
}
a+b
obj1+obj2 (error)

Operator overloading
=================
we cannot perform direct operations on object in c++ if we want to perform
operation on the object then we need to go for operator overloading first then
we can perform operations on objects

almost all opertors can be obe overloading but some can be overloaded such as:
1..(dot)
2.::
3.sizeof()
4.:?

operator ovrloading can be perfomed on unary & binary operators


operator overloading can be perform in to ways
1. member function of the class
2. friend function of the class

unary binary
mem func zero one

friend fun one two

syn
===
return_type operator operator(arg)
{
}
unary operator overloading using mem function(Pre-increment)++
======================================================
#include<iostream>
using namespace std;
class op
{
int a;
public: op(int x=0)
{
a=x;
}
void show()
{
cout<<a<<endl;
}
friend void operator ++(op &,int );
};
void operator ++(op &s,int v)//operator overloading with mem func
{
s.a=s.a++;
}
int main()
{
op obj1(10);
obj1.show();//10
obj1++;//increment on object
obj1.show();//10
}
unary operator overloading using friend function(Pre-increment)++
======================================================

#include<iostream>
using namespace std;
class op
{
int a;
public: op(int x=0)
{
a=x;
}
void show()
{
cout<<a<<endl;
}
friend void operator ++(op &);
};
void operator ++(op &s)//operator overloading with mem func
{
++s.a;
}
int main()
{
op obj1(10);
obj1.show();//10
++obj1;//increment on object
obj1.show();//11
}

unary operator overloading using member function(post-increment)++


======================================================

#include<iostream>
using namespace std;
class op
{
int a;
public: op(int x=0)
{
a=x;
}
void show()
{
cout<<a<<endl;
}
void operator ++( int);
};
void op::operator ++(int v)//operator overloading with mem func
{
a=a++;//a++
}
int main()
{
op obj1(10);
obj1.show();//10
obj1++;//increment on object
obj1.show();//11
}

unary operator overloading using friend function(Post-increment)++


======================================================

#include<iostream>
using namespace std;
class op
{
int a;
public: op(int x=0)
{
a=x;
}
void show()
{
cout<<a<<endl;
}
friend void operator ++(op &,int );
};
void operator ++(op &s,int v)//operator overloading with mem func
{
s.a++;
}
int main()
{
op obj1(10);
obj1.show();//10
obj1++;//increment on object
obj1.show();//11
}

#include<iostream>
using namespace std;
class op
{
int a;
public: op(int x=0)
{
a=x;
}
void show()
{
cout<<a<<endl;
}
friend void operator ++(op &,int );
};
void operator ++(op &s,int v)//operator overloading with mem func
{
s.a=s.a++;
}
int main()
{
op obj1(10);
obj1.show();//10
obj1++;//increment on object
obj1.show();//10
}

unary operator overloading using mem function(Pre-decrement)--


======================================================
#include<iostream>
using namespace std;
class op
{
int a;
public: op(int x=0)
{
a=x;
}
void show()
{
cout<<a<<endl;
}
void operator --( );
};
void op :: operator --()//operator overloading with mem func
{
--a;
}
int main()
{
op obj1(10);
obj1.show();
--obj1;
obj1.show();
}

unary operator overloading using friend function(Pre-decrement)--


======================================================

#include<iostream>
using namespace std;
class op
{
int a;
public: op(int x=0)
{
a=x;
}
void show()
{
cout<<a<<endl;
}
friend void operator --(op &);
};
void operator --(op &s)//operator overloading with mem func
{
--s.a;
}
int main()
{
op obj1(10);
obj1.show();//10
--obj1;//increment on object
obj1.show();//11
}

\
unary operator overloading using member function(post -decrement)--
======================================================

#include<iostream>
using namespace std;
class op
{
int a;
public: op(int x=0)
{
a=x;
}
void show()
{
cout<<a<<endl;
}
void operator --( int);
};
void op::operator --(int v)//operator overloading with mem func
{
a=a--;//a--
}
int main()
{
op obj1(10);
obj1.show();
obj1--;
obj1.show();
}

unary operator overloading using friend function(Post-decrement)--


======================================================

#include<iostream>
using namespace std;
class op
{
int a;
public: op(int x=0)
{
a=x;
}
void show()
{
cout<<a<<endl;
}
friend void operator --(op &,int );
};
void operator --(op &s,int v)//operator overloading with mem func
{
s.a=s.a--;
}
int main()
{
op obj1(10);
obj1.show();
obj1--;
obj1.show();
}

Binary operator oveloading


========================
binary operator using member function (addition) +
=======================================
#include<iostream>
using namespace std;
class op
{
int a,b;
public : //op()
{
}
op(int x=0, int y=0)
{
a=x,b=y;
}
void show()
{
cout<<a<<" "<<b<<endl;
}
void operator +(op &);
};
void op::operator +(op &o2)
{
op o3;
o3.a=a+o2.a;//8
o3.b=b+o2.b;//10
o3.show();//8 10
}
int main()
{
op o1(2,3);
o2(6,7);
o1.show();//2 3
o2.show();//6 7
o1+o2;
}

binary operator using friend functions addition(+)


======================================
#include<iostream>
using namespace std;
class op
{
int a,b;
public : op()
{
}
op(int x, int y)
{
a=x,b=y;
}
void show()
{
cout<<a<<" "<<b<<endl;
}
friend void operator +(op &,op &);
};
void operator +(op &o1,op &o2)
{
op o3;
o3.a=o1.a+o2.a;//8
o3.b=o1.b+o2.b;//10
o3.show();//8 10
}
int main()
{
op o1(2,3);
op o2(6,7);
o1.show();//2 3
o2.show();//6 7
o1+o2;
}

binary operator using member function (subtraction) -


=======================================
#include<iostream>
using namespace std;
class op
{
int a,b;
public : op()
{
}
op(int x, int y)
{
a=x,b=y;
}
void show()
{
cout<<a<<" "<<b<<endl;
}
void operator -(op &);
};
void op::operator -(op &o2)
{
op o3;
o3.a=a-o2.a;//8
o3.b=b-o2.b;//10
o3.show();//8 10
}
int main()
{
op o1(2,3);
o2(6,7);
o1.show();//2 3
o2.show();//6 7
o1-o2;
}

binary operator using friend function sub(-)


======================================
#include<iostream>
using namespace std;
class op
{
int a,b;
public : op()
{
}
op(int x, int y)
{
a=x,b=y;
}
void show()
{
cout<<a<<" "<<b<<endl;
}
friend void operator -(op &);
};
void operator -(op &o1,op &o2)
{
op o3;
o3.a=o1.a-o2.a;//8
o3.b=o1.b-o2.b;//10
o3.show();//8 10
}
int main()
{
op o1(2,3);
op o2(6,7);
o1.show();//2 3
o2.show();//6 7
o1-o2;
}

logical && using mem fun


==================
#include<iostream>
using namespace std;
class op
{
int a,b;
public : op()
{
}
op(int x, int y)
{
a=x,b=y;
}
void show()
{
cout<<a<<" "<<b<<endl;
}
void operator &&(op &);
};
void op::operator &&(op &o2)
{
op o3;
o3.a=a&&o2.a;//8
o3.b=b&&o2.b;//10
o3.show();//8 10
}
int main()
{
op o1(2,3);
o2(6,7);
o1.show();//2 3
o2.show();//6 7
o1&&o2;
}
logical && using friend fun
==================

#include<iostream>
using namespace std;
class op
{
int a,b;
public : op()
{
}
op(int x, int y)
{
a=x,b=y;
}
void show()
{
cout<<a<<" "<<b<<endl;
}
friend void operator &&(op &,op &);
};
void operator &&(op &o1,op &o2)
{
op o3;
o3.a=o1.a&&o2.a;//8
o3.b=o1.b&&o2.b;//10
o3.show();//8 10
}
int main()
{
op o1(2,3);
op o2(6,0);
o1.show();//2 3
o2.show();//6 7
o1&&o2;
}

bitwise & using mem fun


==================
#include<iostream>
using namespace std;
class op
{
int a,b;
public : op()
{
}
op(int x, int y)
{
a=x,b=y;
}
void show()
{
cout<<a<<" "<<b<<endl;
}
void operator &(op &);
};
void op::operator &(op &o2)
{
op o3;
o3.a=a&o2.a;//8
o3.b=b&o2.b;//10
o3.show();//8 10
}
int main()
{
op o1(2,3);
op o2(6,7);
o1.show();//2 3
o2.show();//6 7
o1&o2;
}

Assigment operator using mem fun


==========================
#include<iostream>
using namespace std;
class op
{
int a;
public :
op(int x=0)
{
a=x;
}
void show()
{
cout<<a<<endl;
}
void operator =(op &);
};
void op::operator =(op &o2)
{
a=o2.a;
}
int main()
{
op o1(2);
op o1(4);//syn error object o1 is already created can cannot be
redeclared or assigned with any value
op o2;
o1.show();
o1=o2;
o2.show();

}
Assignment operator cannot be overloaded using friend function
=====================================================

#include<iostream>
using namespace std;
class op
{
int a;
public :
op(int x=0)
{
a=x;
}
void show()
{
cout<<a<<endl;
}
friend void operator =(op &,op &);
};
void operator =(op &o1,op &o2)
{
o1.a=o2.a;
}
int main()
{
op o1(2);
op o3;
op o2;
o1.show();
o1=o2;
o2=o3;
o2.show();

overloading >> << operators


========================
the >> << operator are ones that work for input & output with cin & cout objects
-> we cannot overload these operators with the help of member function
-> it can be only overloaded with friend function & there a specifice logic to
overload these opeartors

Using friend func:


=============

friend void operator <<(ostream&,class &);


friend void operator >>(istream&,class &);

#include<iostream>
using namespace std;
class point
{
int a;
public :
friend void operator <<(ostream&,point &);
friend void operator >>(istream&,point &);
};
void operator <<(ostream &co,point &p)
{
co<<"a="<<p.a<<endl;
}
void operator >>(istream &ci,point &p)
{
ci>>p.a;
}

int main()
{
point obj;
cin>>obj;
cout<<obj;
}

#include<iostream>
using namespace std;
class point
{

int a;
public :
friend void operator <<(ostream &,point &);
friend void operator >>(istream &,point &);
};
void operator <<(ostream &co,point &p)
{
co<<"a="<<a<<endl;
}
void operator >>(istream &ci,point &p)
{
ci>>a;
}

int main()
{
point obj;
cin>>obj;
cout<<obj;
}

================================================================================
==============

inheritance
=========
Mechanism of reusing and extending existing classes
without modifying them.

Newly created classes -----------------derived classes/sub


classes/child classes

Existing class--------------------base class/super class/parent


class

Advantages:

Reusability

Extendibility

Easy debugging

Private attributes of a class are inherited but


inaccessible in an inherited class

Protected attributes of a class are inherited as well as


accessible in the inherited class.

syn inheritance
=============
class parent
{
data mem,
mem func
{
}
};
class child : mode parent
{
}

we cannot inherit certain things from the parent class as they are unique to
class
1.constructors
2.destructor
3.copy constructor
4.operator overloading
5.friend function.

class parent
{
int a;
mem1()
{
}
public : int b;
mem()
{
}
protected : int b;
mem()
{
}
};
class child : private parent
{
};

Public Inheritance: public members of the base class


become public members of the derived class
protected members of the base class become protected
members of the derived class.
A base class's private members are never accessible directly
from a derived class, but can be accessed through calls to the
public and protected members of the base class.

Protected Inheritance: When deriving from a protected


base class, public and protected members of the base class become protected
members of the derived class.

Private Inheritance: When deriving from a private base


class, public and protected members of the base class
become private members of the derived class.

single inhertance
==============
class base
{
};
class derived: mode parent
{
};

example1
========
#include<iostream>
using namespace std;
class shape
{
protected: int width,height;
public: void set_width(int w)
{
width=w;
}
void set_height(int h)
{
height=h;
}
int area();
};
class Rect: public shape
{
int area()
{
return width*height;
}
};
int main()
{
Rect r;
r.set_width(5);
r.set_height(4);
cout<<r.area()<<endl;
}

#include<iostream>
using namespace std;
class shape
{
private: int width,height,h1,w1;
public: void set_width(int w)
{
int w1;
width=w;
w1=width;
}
void set_height(int h)
{

height=h;
h1=height;
}
int area();//this is valid
};
class Rect: public shape
{
int area()
{
return w1*h1;//error local variable
}
};
int main()
{
Rect r;
r.set_width(5);
r.set_height(4);
cout<<r.area()<<endl;
}

Multilevel inhertance
================
class base
{
//base class property
};
class dervied1 :public base
{
//base, derv1 class property
};
class derived2: public dervied1
{
//base,derv1,dev2 class property
};

#include<iostream>
using namespace std;
class shape
{
protected:int width,height;
public: void set_width(int w)
{

width=w;

}
void set_height(int h)
{

height=h;

};
class Rect: public shape
{
public: int area()
{
return width* height;//error local variable
}
};
class Tri: class Rect
{
public:
void display()
{
cout<<"hello this is a triangle class\n";
}
};
int main()
{
Tri r;
r.set_width(5);
r.set_height(4);
cout<<r.area()<<endl;
r.display();
}

Heirarchical inheritance
===================

class base
{
};
class der1:public base
{
};
class der2: public base
{
};

#include<iostream>
using namespace std;
class number
{
protected :int x;
public: void set_val(int a)
{
x=a;
}
};
class sqaure : public number
{
public: int sqr()
{
return x*x;
}
};
class cub:public number
{
public :int cube()
{
return x*x*x;
}
};
int main()
{
square s;
cub c;
s.set_val(5);
cout<<s.sqr()<<endl;
c.set_val(2);
cout<<c.cube()<<endl;
}

Multiple inheritance:
===================
class base
{
};
class base1
{
};
class der: public base,public base1
{
};

example:
#include<iostream>
#include<string.h>
using namespace std;
class par1
{
protected:
char clr[20];

};
class par2
{
protected:
float height;

};
class child:public par1,public par2
{
public:
void chi_init()
{
strcpy(clr,"black");
height=5.5;
}
void print()
{
cout<<"clr-->"<<clr<<"\nheight-->"<<height<<endl;
}

};
int main()
{
child c;
c.chi_init();
c.print();
}

Hybrid inheritance
===============
class base
{
base prperty
}

class der1: public base


{
base propert
//der1 property
};
class der2: public base
{
base
der2
};
class der3:public der1, public der2
{
base,der1
base,der2
};

example:
======
#include<iostream>
using namespace std;
class animal
{
int weight;
public: int get_weight()
{
weight=20;
return weight;
}
};
class tiger: public animal
{
};
class lion: public animal
{
};
class liger : public tiger, public lion
{
};
int main()
{
liger lg;
cout<<lg.get_weight()<<endl;
};

this code will provide a death of diamond or ambiguity error becuase the base
class properties are inherited multiple times via lion class & tiger class so
liger class causes a death of diamond issue..

but this issue can be solved by using a virtual keyword:


=======================

#include<iostream>
using namespace std;
class animal
{
int weight;
public: int get_weight()
{
weight=20;
return weight;
}
};
class tiger: virtual public animal
{
};
class lion: virtual public animal
{
};
class liger : public tiger, public lion
{
};
int main()
{
liger lg;
cout<<lg.get_weight()<<endl;
};

constructor call & destructor call


=========================

class par1
{
public: par1()
{
cout<<"par1 constructor\n";
}
~par1()
{
cout<<"par1 destructor\n";
}
};
class par2
{
public: par2()
{
cout<<"par2 constructor\n";
}
~par2()
{
cout<<"par2 destructor\n";
}
};
class child: public par1,public par2
{
public: child()
{
cout<<"child constructor\n";
}
~child()
{
cout<<"child destructor\n";
}
};

int main()
{
child ch;
}

example 2

#include<iostream>
using namespace std;
class par1
{
public: par1()
{
cout<<"par1 constructor\n";
}
~par1()
{
cout<<"par1 destructor\n";
}
};
class par2
{
public: par2()
{
cout<<"par2 constructor\n";
}
~par2()
{
cout<<"par2 destructor\n";
}
};
class par3
{
public: par3()
{
cout<<"par3 constructor\n";
}
~par3()
{
cout<<"par3 destructor\n";
}
};
class child: public par1,virtual public par2,virtual public par3
{
public: child()
{
cout<<"child constructor\n";
}
~child()
{
cout<<"child destructor\n";
}
};

int main()
{
child ch;
}

function overridding
================
the function with the same name same number of arguments even if they donot
follow any function signatures is known as function overridding
the function overriding can be achieved by inheritance either single level or
multilevel inheritance

function overriding comes under runtime polymorphism that is late binding

example of function overriding


=======================
class A
{
public:
void display()
{
cout<<"this is A\n";
}
};

class B:public A
{
public:
/*void display()
{
cout<<"this is B\n";
}*/
};
class C:public B
{
public:
/*void display()
{
cout<<"this is C\n";
}*/
};

int main()
{
C obj;
obj.display();
}

normally function overriding can be done in two ways


1.upcasting
2.by using virtual function

upcasting:
when we have a base class pointer pointing to the derived class object then
technically it is termed as upcasting

der obj;
Base *b;
b=&obj;

#include<iostream>
using namespace std;
class base
{
public:
virtual void display()
{
cout<<"this is my base class\n";
}
};
class derived: public base
{
void display()
{
cout<<"this is my derived class\n";
}
};
int main()
{
base *ptr;//pointer varaible obj
derived obj;//normal object
ptr=&obj;//upcasting
ptr->display();
obj.display();
}

to achieve a runtime polymorphism we need to make our base class function as


virtual so that late binding will be taken place when we make the base class
function as virtual then it is inherited in the derived class but it will
consider as invisible....

late binding:
==========
func call instead of executing at compile tile if we want to resolve at runtime
then we can make our function as virtual in the base call..

mechanism of late binding


====================
->the virtual keyword to a function can be applied only inside the base class
that means child class cannot have any virtual function
-> whenever we say that the function is virtual then at the runtime the compiler
will a virtual table and a virtual pointer
which is also known as Vtable or Vptr at runtime we also perform upcasting that
means we deal with pointer & address so the address of the object is stored
inside the vtable and the pointer points to the address of that object stored
inside the vtable.

#include<iostream>
using namespace std;
class par
{
int a;
public:
virtual void fun()
{
cout<<"in parent:"<<endl;
}
};
class der:public par
{
int b;
public:
void fun()
{
cout<<"in child:"<<endl;
}
};
int main()
{
par *p;
der obj;
p=&obj;
p->fun();
}

Pure virtual function


================

if a class has a function equated to zero then we say it is a pure virtual


function. a pure virtual function acts as a dummy function so whenever we have a
purevirtual function inside the class we say that class is an abstract class.
Abstract class is just for presence and it has no object created because if a
class is abstract then we cannot instantiate an abstract class.

#include<iostream>
using namespace std;
class par
{
public:
virtual void show()=0;//pure virtual function

};
class child:public par
{
int a;
public:
child(int x)
{
a=x;
}
void show()
{
cout<<"inside show a= "<<a<<endl;
}

};
int main()
{
par *t;
child o(10);
t=&o;
t->show();
}

#include<iostream>
using namespace std;
class par
{
public:
virtual void show()=0;//pure virtual function

};
class child:public par
{
int a;
public:
child(int x)
{
a=x;
}
void show()
{
cout<<"inside show a= "<<a<<endl;
}

};
int main()
{
par *t;
child ob;
t=&ob;
t->show();
//ob.show();creating this way of calling the purew virtual function
is inccorrect because its actually declared in the
parent class only with help of parent class pointer we can access the
pure virtual function
}

Note: since we are declaraing a function as pure in parent class and we are
defining in the child class there is a connection between the parent & child and
only by using the child class obj we cannot access the pure virtual function
defintion we need to make use of the pointer of the parent class then it is
accesible.

#include<iostream>
//in abstract class we can have pointer variable of abstract class but cannot
have normal variable(thz prgrm will wrk without any error)
using namespace std;
class A//abstract class
{
public:
virtual void show()=0;//pv

};
class B:public A
{
public:
void show()
{
cout<<"in derived\n";
}
};
int main()
{
A *bp=new B;//dynamic
bp->show();

//A *p;
B obj;
p=&obj;
p->show();

}
#include<iostream>
using namespace std;
class par
{
public:
par()
{
cout<<"in par constructor:\n";
}
virtual void show()=0;

};
class der:public par
{
public:
der()
{
cout<<"der constructor:\n";
}
void show()
{
cout<<"in derived :\n";
}
};
int main()
{
par *p=new der;
p->show();
}

C++ Templates:
Template is simple and yet very powerful tool in C++.

The simple idea is to pass data type as a parameter so that we don’t need to
write same code for different data types.

C++ adds two new keywords to support templates: ‘template’ and ‘typename’.
The second keyword can always be replaced by keyword ‘class’.

How templates work?


Templates are expanded at compiler time.

compiler does type checking before template expansion.

The idea is simple, source code contains only function/class, but compiled code
may contain multiple copies of same function/class.

simple c++ codes where we need to write different set of codes for different
datatypes

#include<iostream>
using namespace std;
int max(int x, int y)
{
return (x>y)?x:y;
}
double max1(double a,double b)
{
return (a>b)?a:b;
}
int main()
{
max(10,20);
max1(7.8,9.8);
}

syntax for template


================
template<typename place holder>

placeholder fun_name(placeholder var,placeholder var)


{
}

the same previous code to be written using template


=======================================
template< typename T>
T mymax(T x,T y)
{
return (x>y)?x:y;

}
int main()
{
cout<<mymax<int>(3,5)<<endl;
cout<<mymax<double>(3.5,6.8)<<endl;
}

#include<iostream>
using namespace std;
template <class i>
i add(i x,i y)
{

return x+y;
}
template <typename c>
c sub(c x,c y)
{
return x-y;
}
int main()
{
cout<<add<int>(5,6)<<endl;;
cout<<sub<int>(5,2)<<endl;;
}

using two different types of data along with two different placeholder
=================================================
#include<iostream>
using namespace std;
template <class i,class j>
j add(i x,j y)
{

return x+y;
}
template <typename c>
c sub(c x,c y)
{
return x-y;
}
int main()
{
cout<<add<int,double>(5,6.7)<<endl;;
cout<<sub<int>(5,2)<<endl;;
}

Template classes
=============
#include<iostream>
using namespace std;
template<class t>
class test
{
t a;
public: test(t x)
{
a=x;
}
void show()
{
cout<<a<<endl;
}
};
int main()
{
test<int>obj(12);
test<double>obj2(6.8);
test<float>obj3(8.7);
test<char>obj4('m;);
obj1.show();
obj2.show();
obj3.show();
obj4.show();
}

declaring a function in th class & defining it outside the class needs a


template to again written before the function defination
================================================================================
============

#include<iostream>
using namespace std;
template<class t>
class test
{
t a;
public: test(t x)
{
a=x;
}
void show();

};
template<class t>
void test<t>::show()
{
cout<<a<<endl;
}
int main()
{
test<int>obj(12);
test<double>obj2(6.8);
test<float>obj3(8.7);
test<char>obj4('m');
obj.show();
obj2.show();
obj3.show();
obj4.show();
}

can we have more than one argument in a template


======================================
#include<iostream>
using namespace std;
template<class s ,class p>
class test
{
s a;
p b;
public:test()
{
cout<<"this is my constructor\n";
}
void display()
{
cout<<a<<" "<<b<<endl;
}
};
int main()
{
test<char,double>obj1;
test<int,float>obj2;
obj1.display();
obj2.display();
}

example 2
========
#include<iostream>
using namespace std;
template<class s ,class p>
class test
{
s a;
p b;
public:test(s x,p y)
{
a=x;
b=y;
cout<<"this is my constructor\n";
}
void display()
{
cout<<a<<" "<<b<<endl;
}
};
int main()
{
test<char,double>obj1('a',6.7);
test<int,float>obj2(89,7.5);
obj1.display();
obj2.display();
}

can we specify default values for template arguments?

#include<iostream>
using namespace std;
template<class T,class U=char>
class A
{
public: T a;
U b;
A(T x,U y)
{
a=x,b=y;
cout<<"this si constructor\n";
}
};

int main()
{
A<char> a('g','h');
}

example 2

#include<iostream>
using namespace std;
template<class T=char,class U=char>
class A
{
public: T a;
U b;
A(T x,U y)
{
a=x,b=y;
cout<<a<<" "<<b<<endl;
cout<<"this si constructor\n";
}
};

int main()
{
A<>a('g','h');//we have used both the obj name & var name same
so no conflict will occur
}

C style strings
============
handling strings in c++
just like c we can deal with the strings in c++
1.c style
2.String

the header used in c++ is #include<cstring>

#include<iostream>
using namespace std;
int main()
{
char str[5];
cout<<"enter the string\n";
cin>>str;
cout<<a<<endl;
}

reading & printing strings along with spaces


================================
#include<iostream>
using namespace std;
int main()
{
char str[15];
cout<<"enter the string\n";
cin.get(str,13);//cin>>str;
cout<<str<<endl;
}

implementation of string
================
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
String str1="hello";
String str2="world";
String str3,str4;
//length of the string
int len;
len=str2.size();
cout<<"the len of the string is"<<endl;
//coping a string into another
str3=str2;
cout<<str3<<endl;
//concatenation of the string
str4=str1+str2;
cout<<"the concatenated string is "<<str4<<endl;
}
String comparision
===============
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
string s1,s2;
cout<<"enter the two string\n";
cin>>s1;
cin>>s2;
if(s1.compare(s2))
cout<<"not equal\n";
else
cout<<"equal\n";
}

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
string s1,s2;
cout<<"enter the two string\n";
getline(cin,s1);//cin>>s1;
getline(cin,s2);
if(s1.compare(s2))
cout<<"not equal\n";
else
cout<<"equal\n";
}

STL(standard template library)


========================
the c++ STL library is a powerful set of C++ classes and templates to provide a
general purpose programming with templates that implement many popular &
commonly used algorithms and data structures like vectors, list , queues and
stack

in the core library of C++ standard template there are three well structured
components

1.container: containers are used to manage collections of objects of certain


kind .. there are several different types of containers example vectors lists &
maps
2.algorithms: they also act as containers they actually provide the means by
which we can perform initialization,sorting,searching, transferring
3.iterators: iterators are used to step through the elemnts of collections of
objects. these collections may be containers.

#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> vec;
int i;
cout<<"vector size="<<vec.size()<<endl;

for(i=0;i<5;i++)
{
vec.push.back(i);
}

for(i=0;i<5;i++)
{
cout<<"values are"<<vec[i]<<endl;
}
}

combination of ierators with vectors


===========================

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
vector<int> vec;
int i;
cout<<"vector size="<<vec.size()<<endl;

for(i=0;i<5;i++)
{
vec.push_back(i);
}
cout<<"vector size="<<vec.size()<<endl;

/* for(i=0;i<5;i++)
{
cout<<"values are"<<vec[i]<<endl;
}*/
vector<int>::iterator v=vec.begin();
while(v!= vec.end())
{
cout<<"values are"<<*v<<endl;//an iterator value is considered to
be a pointer varaible so when we need
// to print the values through iterator we need dereferencing a
pointer
v++;
}
}

Stack
=====
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<int> st;
st.push(10);
st.push(20);
st.push(30);
cout<<st.top()<<endl;
st.pop();
st.top()=88;
st.push(40);
st.push(50);
st.pop();
while(!st.empty())
{
cout<<st.top()<<endl;
st.pop();
}
}

#include<iostream>
#include<queue>
#include<string>
using namespace std;
int main()
{
queue<string> q;
q.push("these ");
q.push("are ");
q.push("more than ");
cout<<q.front()<<endl;
q.pop();
cout<<q.front()<<endl;
q.pop();
q.push("four ");
q.push("words ");
q.pop();
cout<<q.front()<<endl;
q.pop();
cout<<q.front()<<endl;
q.pop();
cout<<q.size()<<endl;
}

List
====
#include<iostream>
#include<list>
using namespace std;
int main()
{
list<int> lst;
int i;
for(i=0;i<10;i++)
lst.push_back(i);
cout<<"size="<<lst.size()<<endl;
list<int>:: ierator p=lst.begin();
while(p!=lst.end())
{
cout<<*p<<endl;
p++;
}
}
modified list
============
#include<iostream>
#include<list>
using namespace std;
int main()
{
list<int> lst;
int i;
for(i=0;i<10;i++)
lst.push_back(i);
cout<<"size="<<lst.size()<<endl;
list<int>:: iterator p=lst.begin();
while(p!=lst.end())
{
cout<<*p<<endl;
p++;
}
p=lst.begin();
while(p!=lst.end())
{
*p=*p+10;
p++;
}
cout<<"after modification\n";
p=lst.begin();
while(p!=lst.end())
{
cout<<*p<<endl;
p++;
}
}

Fill algorithm
============
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
vector<int> myvector(8); //0 0 0 0 0 0 0 0
fill(myvector.begin(),myvector.begin()+4,5);5 5 5 5 0 0 0 0
fill(myvector.begin()+3,myvector.end()-2,8);5 5 5 8 8 8 0 0
for(vector<int>::iterator i=myvector.begin(); i!=myvector.end();++i)
cout<<*i<<endl;
}

copy algorithm
===========
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int myints[]={1,2,3,4,5,6,7,8,};
vector<int> myvector(8);
copy(myints,myints+8,myvector.begin());
for(vector<int>.iterator i=myvector.begin();i!=myvector.end();++i)
cout<<*i<<endl;
}

//count algorithm
//find algorithm

You might also like