c++ total concepts

66
Introduction Of C++ C++ acquire the feature of high level and low level language C++ compiled and general purpose programming language. In 1979 Bjarne Stroustrup extended C programming language known as C with Classes at Bell Labs. In 1983 the C with Classes is became C++. C++ is used in System software, application software, device drivers, embedded software, high-performance server and client applications, and entertainment software such as video games. History of C++ C++ was developed by Bjarne Stroustrup in 1983 at AT&T Bell lab . Bjarne Stroustrup began work on "C with Classes" in 1979.Beginning of 1981 initial version of c++ ware made internally in AT&T lab. In c++ ,"++" is the increment operator of c which means its an extension of C Language. C++ is a superset of C, so that most C programs can be compiled using a C++ compiler i.e. C language have series of low-level instructions that converted into C++ the computer can execute directly. But C not support C+ +. In C++, include OOP (Object Oriented Programming) features when the significance of C is same in C++. In OOP, the programmer defined not only the data type of Data Structure (DS) but also the operations that is applied on DS . The DS known as object have both data type and operation. Advantage and Disadvantage Advantage of C++ are : C++ use multi-paradigm programming. Paradigm means style of programming .paradigm concerned about logics , structure and procedure of program. C++ is multi-paradigm means it follow three paradigm Generic, Imperative, Object Oriented. C++ provide performance and memory efficiently. It is useful for low level programming language and very efficient for general purpose. It provide high level abstraction in the language of the problem domain. C++ is compatible with C. C++ used reusability of code. C++ used inheritance, polymorphism. Disadvantage of C++ are : Complex in very large high level program. Used for platform specific application commonly.

Upload: sumant-lohar

Post on 13-Apr-2015

28 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: C++ Total Concepts

Introduction Of C++

C++ acquire the  feature of high level and low level language C++ compiled and general purpose programming language. In 1979 Bjarne Stroustrup extended C programming language known as C with Classes at Bell Labs. In 1983 the C with Classes is became C++. C++ is used in System software, application software, device drivers, embedded software, high-performance server and client applications, and entertainment software such as video games.

 

History of C++

C++ was developed by Bjarne Stroustrup in 1983 at AT&T Bell lab. Bjarne Stroustrup began work on "C with Classes" in 1979.Beginning of 1981 initial version of c++  ware made internally in AT&T lab. In c++ ,"++" is the increment operator of c which means its an extension of  C Language. C++ is a superset of C, so that most C programs can be compiled using a C++ compiler i.e. C language have series of low-level instructions that converted into C++ the computer can execute directly. But C not support C++. In C++,  include  OOP (Object Oriented Programming) features when the significance of C is same in C++. In OOP, the programmer defined not only the data type of Data Structure (DS) but also the operations that is applied on DS . The DS known as object have both data type and operation.

 

Advantage and Disadvantage

Advantage of C++ are:

C++ use multi-paradigm programming. Paradigm means style of programming .paradigm concerned about logics , structure and procedure of program. C++ is multi-paradigm means it follow three paradigm Generic, Imperative, Object Oriented.

C++ provide performance and memory efficiently. It is useful for low level programming language and very efficient for general

purpose. It provide high level abstraction in the language of the problem domain. C++ is compatible with C. C++ used reusability of code. C++ used inheritance, polymorphism.

Disadvantage of C++ are:

Complex in very large high level program. Used for platform specific application commonly. For a particular operating system or platform the library set is usually chosen that

locks.  when C++ used for web applications complex and difficult to debug . C++ can't support garbage collection. C++ not support Dynamic Memory Allocation. C++ is not secure because it have pointer, friend function and global variable. No support for threads built in.

Scope of the C++

Page 2: C++ Total Concepts

Scope of the C++ is:

C++ use with object oriented programming. C++ used object where object are real time entities. C++ used class ,is a container of objects. C++ provide reusability of codes. In C++ , functions and variable can acquire the feature  of its parents. In C++, function can be overloaded and override. C++ can use encapsulation. 

The Parts of a C++ Program

C++ program have variable ,function ,objects, other component. These are the C++ program parts:Hello Program in C++:

#include <iostream> //include header file using namespace Beg;

int main() { cout << "Hello world.\n"; //C++ statement

return 0; } Hello world.

Header File :This function is include the header files. Header files have predefined functions and variables or resources that are to be shared between parts of different program.

Comment : comment is used for documentation and start with // symbol. C++ have two type of comments -Single line comment start with // and end when line is end.

Multiple line comments start with /* and end with */.

In namespace a block of code written here .and also through namespace reduce the collision.

main is a function. Execution begins with the main(). This tells that which type of variable return .

count is a predefined object that represent the standard output Stream.

return is the function . It return a variable or value when call this function.

 Variables of C++

A variable is the temporary storage space in memory stored by its value. variable can be represented by their name . The variable name can be any think like set of one or more letters, digits or underscore.

Page 3: C++ Total Concepts

Rules for defining variable name:

A variable name can have set of letters or digits or underscore . A variable name can't have White space, punctuation symbols or other characters

. A variable name must begin with a letter. Keywords or any reserved words cannot be of variable names. Variable names written in capital letters and small letters are different variable

because C++ is a case-sensitive language

Declaration of variables:

before declaring a variable first should think about data type of variable and also the name of the variable .Name of the variable should have some meaning .Data type in C++ is as:

data_type  variable_name;

short int :used to represent short integer. int: used to represent integer. long int: used to represent long integer.float: used to represent floating point number.double: used to represent double precision floating point number.long double: used to represent double precision floating point number.char: used to represent a single character. bool: used to represent two values: True or False.

Type Size Values

unsigned short int 2 bytes 0 to 65,535

short int 2 bytes –32,768 to 32,767

unsigned long int 4 bytes 0 to 4,294,967,295

long int 4 bytes –2,147,483,648 to 2,147,483,647

int 4 bytes –2,147,483,648 to 2,147,483,647

unsigned int 4 bytes 0 to 4,294,967,295

char 1 byte character values

bool 1 byte true or false

float 4 bytes 1.2e–38 to 3.4e38

double 8 bytes 2.2e–308 to 1.8e308

#include <iostream> //include header file using namespace Beg;

int main() //main function with int return type {

int a; // declaration int sum=0; // declaration cin>> a; //object of in stream

cout << "value of a is.\n",a; //object of output streamsum= sum+a; cout << "sum is.\n",sum; //object of output streamreturn 0; //return function

}

Page 4: C++ Total Concepts

value of a.10sum is.10

Reference Variable: A reference variable provide an alias (alternative name) for a previously defined variable name.

data_type & reference_name = variable_name; 

Constant Of C++

constant are like variable  but the difference between constant and variable is that constant value fixed it can't change in whole program but variable value can change during program.

Enumeration ConstantAn enumeration data type, data type represents a set of identifiers. Each identifier in this set is an enumeration constant.

The value of the enumeration constant is determined as:

 In enumeration constant assigned to the explicit value for set of identifier.  If no explicit value is assigned, the leftmost constant in the set of receives the

value zero (0).  If in the set of integer identifiers with no explicitly assigned values that is one

greater than the value represented by the previous identifier.

 

When declare const its must have initializes means in left hand contain the name of constant and in right hand side have the value of that constant except those referencing externally defined constants . If constant is an integer then const object can appear in a constant expression and it is initialized to a constant. The following example:

const int number = 200;int ary[number]; /* allowed in C++*/.If a global const object have no any explicit storage class then it consider as static const by default.

const int number = 12;static const int number1 = 120; extern const int number2 = 121;

Because its linkage is assumed to be internal, a const object can be more easily defined in header files in C++ than in C.

 Expressions

Expression

An expression is a combination of operators, constants and variables. It also include function call which return values. An expression may include one or more operators. The operator in C++ are:

Page 5: C++ Total Concepts

Arithmetic operators

Operator name Syntax Prefix Suffix

Basic assignment a = b

Addition a + b

Subtraction a - b

Unary minus -a

Unary plus +a

Multiplication a * b

Division a / b

Modulo (remainder) a % b

Increment ++ ++a a++

Decrement -- --a a--

Comparison operators/Relational operators

Operator name Syntax

Equal to a ==b

Not equal to a !=b

Greater than a > b

Less than a < b

Greater than or equal to a >=b

Less than or equal to a <=b

Logical operators

Operator name Syntax

Logical negation (NOT) !a

Logical AND a && b

Logical OR a || b

Bitwise operators

Operator name Syntax

Bitwise NOT ~a

Bitwise AND a & b

Bitwise OR a | b

Bitwise XOR  a ^ b

Bitwise left shift a <<b

Bitwise right shift a >>b

Compound-assignment operators

Operator name Syntax

Addition assignment a += b

Subtraction assignment a -= b

Page 6: C++ Total Concepts

Multiplication assignment a *= b

Division assignment a /= b

Modulo assignment a %= b

Bitwise AND assignment a &= b

Bitwise OR assignment a |= b

Bitwise XOR assignment a ^= b

Bitwise left shift assignment a <<=b

Bitwise right shift assignment a >>=b

Type of  Expression:

Constant Expression

Example:

2029+48%2

Integer Expression

Example:

m+n-229+int(222.3)

Float Expression

Example:

m+n294+float(2224)

Pointer Expression

Example:

&mptrptr+1

Relational Expression

Example:

a+b==c+dx<=ym+n>100

Logical Expression

Example:

Page 7: C++ Total Concepts

a>b && x==1098x==200 ||y==20

Bitwise Expression

Example:

a>>1098x<<200

Statement

if Statement:In if statement condition evaluated if condition is true then statement with in if block will be executed otherwise control go to else block will executed.

Simple if statement if_else statement

Simple if statement:

if (expression is true){statement1;}statement2;statement3;

if_else statement:

if (expression is true){statement1;}else{statement2;}statement3;if (x == 203035) // if statement cout << "x is 203035";else //else statement cout << "x is not 203035";

Switch Statement:

This is a multi branching Statement which is based on condition. Control is transfer to one of the many statements.

switch (expression){case 1:{

Page 8: C++ Total Concepts

statement 1:...statement n;}case 2:{statement 1:...statement n;}... .default:{statement 1:...statement n;}}statement;

do while statement:

This is statement where first loop executed then condition evaluated.

do{statement 1;}while (condition is true);statement n ;

while statement:

#include <iostream>using namespace std;

int main (){ int number; cout << "Enter the initial > "; cin >> n;

while (n<10) { cout << n << ", "; ++n; }

cout << "OUT!\n";

Page 9: C++ Total Concepts

return 0;Enter the initial>11,2,3,4,5,6,7,8,9,10,OUT!

for Statement:

for(initial value; test condition; increment/decrement){  statement 1;...statement n;}

Basic Classes  

Class is use for bind data and its operated function together. For external use its necessary to hidden the data and function. Or Class is the container of object.

Class Specification have two part::

Class Declaration Class Function definitions

Class Declaration:

class class_name{private:variable declarations;    function declarations;public:variable declarations;    function declarations;

};

The keyword class specified that what follow in an abstract data of type class_name.private and public are access modifier. where private is visible with is the class where public data member is can be access with in the class and also outside the class.

class class_name{private:int num1;

Page 10: C++ Total Concepts

float num2;public:void getdata(int num1,float num2);void putdata(void);};

Create Objects

Object is real time entity. Object have some attribute and also some feature.Object can created with class name as-

class_name object_name;

And also created as: 

class class_name{private:int num1;float num2;public:void getdata(int num1,float num2);void putdata(void);}c1,c2,c3;                                                                      //object created.

Class Function Definition:

Member function can be defined in two ways:

Out Site the class definition Inside the class definition

Outsite the class definitionreturn_type class_name:: function_name(argument declare){             function body;}

Inside the class definition 

class class_name{

private:int num1;float num2;

public:void getdata(int num1,float num2) // inside class declaration

{cin>>num1;cin>>num2;

}void putdata(void); // inside class declaration

Page 11: C++ Total Concepts

{cout<<num1;cout<<num2;

}}c1,c2,c3; //object created.

Inheritance

In C++ Inheritance is used for reusability of codes. One of the  important feature of OOP is reusability. It's done through creating new classes, and reuse the feature and attribute of existing old one . The mechanism where feature and attribute of an old class is deriving  to a new class is called inheritance. The old class is referred to as the base class and the new one is called the derived class or subclass. The derived class or subclass can acquire the some or all property of base class. Derived class have its own feature and also the feature of its super or base class.

Defining The Derived Class:

Derived class are those classes who inherit the property of  base class. In any program can have many base class and also have many derived classes .

class derived_class_name : access_modifier base_class_name{....... //members 0of derived class........ //members 0of derived class........ //members 0of derived class};

class base{//member of base class};class derive1: private base //private derivation{//member of derived1};class derive2: public base //public derivation{//member of derived2};class derive3: base //private derivation by default{//member of derived3};

Private Inheritance:

when derived class is private inherited the base class then public member of the base class is become private member of the derived class. When a derived class inherit the base class then member function of derived class can only access the public member of base class. when base class is privately inherited then no member of the base class is accessible to the object of derived class.

Page 12: C++ Total Concepts

Public Inheritance:

when derived class is public inherited the base class then public member of the base class is become public member of the derived class. When a derived class inherit the base class then member function of derived class can only access the public member of base class. when base class is publicly inherited then public member of the base class is accessible to the object of derived class. But in both cases private member of the base class can't inherited therefore private members of a base class will never become the member of its derived class.

#include<iostream>

class Rectangle{private:float length ;                           // private member and data can't inheritedpublic:float width ;                            // public member and data are inheritablevoid dimention()                        //  public member and data are inheritable{cout << "\n Enter the length of the rectangle : "; cin >> length ;cout << "\n Enter the width of the rectangle : "; cin >> width ;}float length1()                         // The public member and data are inheritable{ return length ; } };                                      // End of the class definition

class RectangleArea : public Rectangle { private:float area ;public:void Rec_area(void){ area = length1() * width ;             //length can't access directly because its a private member of base class }

void Display(void){cout << "\n Length = " << length1() ; //length can't access directly because its a private member of baseclasscout << "\n width = " << width ;cout << "\n Area = " << area ;}};                                   // End of the derived class definition void main(void){RectangleArea area1 ;area1.length1();                    // The public member and data so its access through the object of derived class.area1.Rec_area( );area1.Display( );}

Page 13: C++ Total Concepts

Types of Inheritance( Single, Multiple)

Single Inheritance Multiple Inheritance Hierarchal Inheritance Multilevel Inheritance Hybrid Inheritance

Single Inheritance:

One derived class inherit the public members of base class. In single inheritance there is single base class and also single derived class .Derived class can access only public member of base class and can access the public member through derived class objects.

Types of Inheritance( Hierarchal, Multilevel, Hybrid)

Hierarchal Inheritance:

In this inheritance ,is use hierarchal design. Here a base class is derived to other two or more derived class and then derived class is become base class for next level derived class. This include multilevel inheritance .  

Page 14: C++ Total Concepts

Structure of Hierarchal Inheritance:

# include<iostream.h>class base {.........                         // class body.....};class derived1:public base{.........                       // class body.....

Page 15: C++ Total Concepts

};class derived2:public base{.........                       // class body.....};class derived3:public base{.........                        // class body.....};class derived2_a:public derived2{.........                        // class body.....};class derived2_b:public derived2{.........                       // class body.....};class derived2_c:public derived2{.........                       // class body.....};Structure of Hierarchal Inheritance:

#include<iostream>const int num = 20 ;class student // Base class{private: char F_name[num] , L_name[num] ;int age, int roll_no ;public:void Enter_data(void){cout << "\n\t Enter the first name: " ; cin >> F_name ;cout << "\t Enter the second name: "; cin >> L_name ;cout << "\t Enter the age: " ; cin >> age ;cout << "\t Enter the roll_no: " ; cin >> roll_no ;}void Display_data(void){cout << "\n First Name = " << F_name ;cout << "\n Last Name = " << L_name ;cout << "\n Age = " << age ;cout << "\n Roll Number = " << roll_no ;}};class arts : public student //derived

Page 16: C++ Total Concepts

class of same base class{private:char subject_name1[num] ;char subject_name2[num] ;char subject_name3[num] ;public:void Enter_data(void){cout << "\t Enter the subject1 : "; cin >> subject_name1 ;cout << "\t Enter the subject2 "; cin >> subject_name2 ;cout << "\t Enter the subject3 "; cin >> subject_name3 ;}void Display_data(void){cout << "\n Subject1 = " << subject_name1 ;cout << "\n Subject2 = " << subject_name2 ;cout << "\n Subject3 = " << subject_name3 ;}};class arts : public student //derived class of same base class{private:char s_subject_name1[num] ;char s_subject_name2[num] ;char s_subject_name3[num] ;public:void Enter_data(void){cout << "\t Enter the subject1 : "; cin >> s_subject_name1 ;cout << "\t Enter the subject2 "; cin >> s_subject_name2 ;cout << "\t Enter the subject3 "; cin >> s_subject_name3 ;}void Display_data(void){cout << "\n Subject1 = " << s_subject_name1 ;cout << "\n Subject2 = " << s_subject_name2 ;cout << "\n Subject3 = " << s_subject_name3 ;}};class commerce : public student //derived class of same base class{private: char c_subject_name[num],c_subject_name2[num],c_subject_name3[num] ;public:

Page 17: C++ Total Concepts

void Enter_data(void){cout << "\t Enter the subject1: ";cin >> c_subject_name;cout << "\t Enter the subject2 : ";cin >>c_subject_name2 ;cout << "\t Enter the subject3 : ";cin >>c_subject_name3 ;}void Display_data(void){cout << "\n Subject1 = " << c_subject_name ;cout << "\n Subject2 = " <<c_subject_name2 ;cout << "\n Subject3 = " <<c_subject_name3 ;}};

void main(void){arts a ;cout << "\n details of the arts student\n" ;a.Enter_data( );cout << "\n details of the arts student\n" ;a.Display_data( );science s ;cout << "\n details of the science student\n" ;s.Enter_data( );cout << "\n details of the science student\n" ;s.Display_data( );commerce c ;cout << "\n details of the commerce student\n" ;c.Enter_data( );cout << "\n details of the commerce student\n";c.Display_data( );}

Multilevel Inheritance:

In multilevel inheritance where a derived class inherit the property on one base class and that derived class is become the base class for another derived class. For example A is a base class and B inherit the property of A here B is a derive class and another class C is inherit the property of class B now class B become the base class for class C and class C is derived class For class B. class A indirectly base Class of Class C and class C indirect derived class for class A. 

Page 18: C++ Total Concepts

Structure of Hierarchal Inheritance:

# include<iostream.h>class base{

....

..... // class body

.....};class derived1:public base // derived from base class{

....

..... // class body

.....

Page 19: C++ Total Concepts

};class derived2:public derived1 // derived from derived class{

....

..... // class body

.....};Structure of Multilevel Inheritance:

# include<iostream.h>class student{

protected:int roll_num;

public:void enter_number(int a)

{roll_num=a;

}void display_number(void)

{cout<<"Enter roll number is"<<roll_num<<"\n";

}};class test : public student //First level derivation{

protected:float subject1:float subject2;

public:void enter_marks(float x, float y)

{subject1=x;subject2=y;

}void display_marks(void)

{cout<<"marks of subject1"<<subject1<<"\n";cout<<"marks of subject2"<<subject2<<"\n";

}};class result : public test //Second level derivation{

float total;public:

void display(void){

total=subject1+subject2;display_number();display_marks();cout<<"total ="<<total<<"\n";

}};

int main(){result re;re.enter_number(100);re.enter_marks(76.5,77.5);re.display();

Page 20: C++ Total Concepts

return 0;}

};

Hybrid Inheritance:

In hybrid Inheritance , this is combination of two or more  type of inheritance . but in hybrid inheritance the error will occur is known as ambiguity . Where same function name can have more then one class then compiler confused to identify called function.

Structure of Hybrid Inheritance:

# include<iostream.h>class student{

protected:int roll_num;

public:void enter_number(int a)

{roll_num=a;

}void display_number(void)

{cout<<"Enter roll number is"<<roll_num<<"\n";

}};class test : public student //First level derivation{

protected:float subject1:float subject2;

public:void enter_marks(float x, float y)

{subject1=x;subject2=y;

}void display_marks(void)

{cout<<"marks of subject1"<<subject1<<"\n";cout<<"marks of subject2"<<subject2<<"\n";

}};class sport{

protected:float score;

public:void enter_ score(int i)

{ score=i;

}void display_ score(void)

{cout<<"Enter score is"<< score<<"\n";

}class result : public test{

Page 21: C++ Total Concepts

float total;public:

void display(void){

total=subject1+subject2+ score;display_number();display_marks();display_ score();cout<<"total ="<<total<<"\n";

};int main()

{result re;re.enter_number(1234);re.enter_marks(27.5,33.0);re.enter_score(6.0);re.display();return 0;}

};OUTPUT:

Enter roll number is 1234marks of subject1 27.5marks of subject2 33Enter score is 6total=66.5

Polymorphism

Polymorphism means one thing in many form. In polymorphism operators and functions can use in many forms. Single operator behave different  for different data type. Such as addition operator use to add integer and concatenate for string. Polymorphism is the concept where one same function or operator send to many different object how perform different operation and result is also different. There are two types of polymorphism:

Static Polymorphism Dynamic Polymorphism

 

Page 22: C++ Total Concepts

Static polymorphism refers to an many similar entity existing in continuous but have slight difference. Static polymorphism many functions have some differences as number, type, and sequence of arguments. When function declaration the various types of parameters are specified ,and therefore the function can be bound to calls at compile time. This phenomena is called early binding. The term early binding  the calls of parameter , return type are already bound to that functions when program is executed. At the time of compilation this function bind that's why its known as early binding.

Function Overloading:

In function overloading provide the facility that with in the same class more then one function can have same name  but the number , type and appearance of the argument or parameter must be changed.

How to declare Function in function overloading:   

void fun(); // Overloadedvoid fun(int i,float j); // Overloadedvoid fun(float j,inti);  // Overloadedvoid fun(int i, int j); // Overloadedvoid fun(int j, int i); // Overloadedint fun(); // Error - function redefined (because only return type is different)

#include <iostream.h>class Maths{

public:int volume(int i)

{return(i*i);

}double volume(double j,int k)

{return(j*k);

}long volume(long l,int x,int y){

return(l*x*y);

Page 23: C++ Total Concepts

} };

Operator Overloading:

Operator overloading  concept where operator overloaded. In general  operator will be applied on variables or on constant but in operator overloading operator use as the name of function and operator applied on object.Types of operator who overload are:

overload plus subtract overload object and primitive data type overload assignment operator overload logic operator overload conversion operator overload pointer operator overload address of operator overload unary operator overload bracket operator overload square bracket overload cast operator overload comma operator overload new operator overload delete operator overload ostream istream operator overload operator with friend overload with friend function overloading Dereference operator custom extractor custom inserter enum operator

#include <iostream>using namespace std;

class Op_overload { int x, y, z;public: Op_overload() { x = y = z = 0; } Op_overload(int i, int j, int k) { x = i; y = j; z = k; }

Op_overload operator+(Op_overload op2); // op1 is implied Op_overload operator=(Op_overload op2); // op1 is implied Op_overload operator-(Op_overload op2); // op1 is implied void show() ;};Op_overload Op_overload::operator-(Op_overload op2) // subtraction overload .{ Op_overloadtemp_store;

temp_store.x = x - op2.x; temp_store.y = y - op2.y; temp_store.z = z - op2.z; returntemp_store;}

Op_overload Op_overload::operator+(Op_overload op2) // addition overload.

Page 24: C++ Total Concepts

{ Op_overloadtemp_store;

temp_store.x = x + op2.x; temp_store.y = y + op2.x; temp_store.z = z + op2.z; returntemp_store;}Op_overload Op_overload::operator=(Op_overload op2) // assignment overload .{ x = op2.x; y = op2.y; z = op2.z; return *this;}

// Show X, Y, Z coordinates.void Op_overload::show(){ cout << x << ", "; cout << y << ", "; cout << z << "\n";}

int main(){ Op_overload a(10, 20, 30), b(100, 100, 100), c;

cout << "value of a: "; a.show(); cout << "value of b: "; b.show();

c = a - c; cout << "a - c: "; c.show();

cout << "\n";

return 0;}OUTPUT:

value of a: 10, 20, 30value of b: 100, 100, 100a - c: 10, 20, 30

Dynamic polymorphism where an entity can modify its form depending on the situation. A function is dynamic polymorphism when one function can have more then one form and the call of various form can be resolved at run time dynamically or at the time of execution. The term late binding refers to the functions resolution at run-time . Late binding give more the flexibility of the program .

Virtual Function:

A function which become virtual function then use virtual keyword. a virtual function is a

Page 25: C++ Total Concepts

member function which is defined in base class and then redefine for other derived classes, and the redefined virtual function will always called by the compiler for an object of the  corresponding derived class, even if called by pointer or reference to a base class of the object to that function. 

A class that declares or inherits a virtual function is called a polymorphic class. 

#include <iostream>using namespace std;

class base{

public:void display()

{cout<<"\n Display base ";

}virtual show()

{cout<<"\n show base ";}

};class derived:public base{

public:void display()

{cout<<"\n Display derived ";

}void show()

{cout<<"\n show derived ";}

};int main()

{base b;derived d;base *bptr;cout<<"\n bptr points to base\n";bptr=&b;bptr->display(); //calls base displaybptr->shoe(); //calls base showcout<<"\n bptr points to derived \n";bptr=&d;bptr->display(); // calls base displaybptr->show(); //calls derived show is virtualreturn 0;

}OUTPUT: bptr points to base

Display baseshow Base

Page 26: C++ Total Concepts

bptr points to derived

Display baseshow derived

Structure Of C++ Program

 Include Files

     Class Declaration

                    Member Function Definitions

                        Main Function Program

Difference Between C And C++

1. C is not an object oriented language (C is a procedural programming language), while C++ is an object oriented language. 

2. In C we use scanf () as standard input function, while in c++ we use cin>> for input. like this for output in c we use printf() while in c++ we use cout<< as a output function. 

3. C does not have the concept of classes and object. 

4. C does not have namespaces while C++ have. 

5. Function overloading is not supported by C. C++ supports function overloading. 

6. C does not have reference variables while C++ uses reference variables. 

7. C++ supports operators overloading, C does not support. 

8. C have top down approach while C++ have bottom up approach.  

9. Data is not structured in C while data is structured in C++. 

10. In C  #include<stdio.h> is used as header file, but in C++  #include<iostream.h> is used as header file. 

11. C does not support C++ programs but C++ support the C program. 

12. C is low level language while C++ is high level language.

Page 27: C++ Total Concepts

13. Description Of the above program :

#include <iostream>:Hash sign (#) are directives for the preprocessor. Directive #include <iostream> tells the preprocessor to include the iostream standard file.

14. using namespace first;All the elements of C++ library are present within a namespace that we have to use in our program.

15. int main ():From the main() the program starts its execution. main() is followed by parenthesis because main() is used as a function.

16. { } (open and close curly braces): Opening braces are used to start execution of  block of code written in it and closing braces are used to end execution of block of code.

17. cout :cout is the output function in C++. It displays output on the screen.

18.  ; (semicolon) :This is used for to mark the end of the statement.

19. return 0 :It tells that main function has finished.

Variables In C++

    Variables are used to allocate memory to some data. A variable must be declared and defined before it can be used in a program. Every variable can store a value. In C++ variables are used to store information.The type of value which the variable store is called Data Types for example int, float, double etc. Variable name is a sequence of one or more letters, digits or underscore, for example: name_. Integer and char variable may be signed and unsigned.

Syntax : <datatype>             <variable names>

Declaration Of Variables :

int a;float x, y, z;

Variable Initialization :char name='mini';

Constants In C++

Constants are also used to store information. The value of constants can't be change. A constant must be initialize before use.C++ have two types of constants.

Literal Constant Symbolic Constant

Literal Constants

A literal constant is a value used directly into the program and it can't be change.For Example : int num=25; here num is a variable of int type, and 25 is a literal constant.

Page 28: C++ Total Concepts

Symbolic Constants

Symbolic constants are represented by a name just like as a variable. Its value can't be change.For Example : If our program has one integer chairs and another is classes, and we want  to get the no. of chairs and we know  there are 20 chairs in each class then we can easily compute.chairs=classes*20

Enumerated Constants

Enumerated constants are used to create new types and then we have to define those variables.For Example : if we declare day to be enumeration then we can define 7 values for days sun, mon, tues, wed, thurs, fri, satSyntax : enum days{sun, mon, tues, wed, thurs, fri, sat};

Operators In C++

The number of operators in C++ is quite large.

1. Arithmetic Operators2. Increment And Decrement Operators3. Relational Operators4. Boolean Operators5. Assignment Operators6. Bitwise Operators

Arithmetic Operators

               Operators

            Function

                     +            Addition

                     -            Subtraction

                     *            Multiplication

                      /            Division

                      %            Modulus

 

Increment And Decrement Operators

                 Operators        Function

                  A++    Post Increment

                   ++A    Pre

Page 29: C++ Total Concepts

Increment

                   A--    Post Decrement

                   --A    Pre Decrement

Relational Operators

                Operators         Function

                     ==        Equality

                     !=        Not Equal

                     <       Less Than

                      >       Greater Than

                      >=       Greater Than Equal

                    <=       Less than Equal

Boolean Operators

             Operators

              Function

                  &&                And

                   ||                 Or

                   !                 Not

Assignment Operators

            Operators

             Function

                 =Assign right side value to left side variable

                 += A+=B means A=A+B

                 - = A-=B means A=A-B

                  *= A*=B means A=A*B

                  /= A/=B means A=A/B

                  %= A%=B means A=A%B

Bitwise Operators

                Operators

             Function

                     &               And

                     |                OR

Page 30: C++ Total Concepts

                     ^               XOR

                     ~               NOT

                     <<               SHL

                      >>               RHL

Statements In C++

There are three types of statements in C++.

Conditional  Statements Looping Statements Jumping Statements

Conditional Statements

Simple if statements if else statements switch statements

Simple if Statements :Syntax :if (expression is true){action 1;}action 2;action 3;

if....else Statements :Syntax :if (expression is true){action 1;}else{action 2;}action 3;

switch Statements :Syntax :switch (expression){case 1:{}action 1;}case 2:{action 2;}case 3:

Page 31: C++ Total Concepts

{action 3;}default :{action 4;}}action 5;

Looping Statements

for while do...while

for Loop :Syntax : for (initial value; condition; expression){action 1;}action 2;

while Loop :Syntax :while (condition is true){action 1;}action 2;

do...while Loop :Syntax :do {action 1;}while (condition is true);

Jumping Statements

goto break continue

goto Statement :A goto statement causes the program to unconditionally transfer control to the statement associated with the goto statement. You cannot use a goto statement to jump over initializations.

break Statement :break statement is used to exit any kind of loop if a specific condition is met.

continue Statement :The continue statement can be used to transfer control to the end of loop body.

Page 32: C++ Total Concepts

Classes In C++

      A class is like structure in C. A class is a way to bind the data and its associated functions in a unit. It allows the data to be hidden. The keyword 'class' is used to define a class. The body of class is enclosed within braces and terminated by a semicolon. These functions and variables collectively called 'class members'. The class body contains the variables and functions All classes members are private by default. A class is inherited privately by default. The arrays can be used as member variables in class.

The class members that have been declared private can be accessed  only within the class. On the other hand public class members can be accessed outside the class.The variables defined in the class is called data members and the functions that are used in the class  is celled member function. We can say that class is a collection of data member and member function.Only the  member function can have access to the private data members and private function, while the public member can be accessed from outside the class.

A class must have end with a semicolon.

Class Declaration :

class class_name{private :   variable declaration;    function declaration;public :   variable declaration;    function declaration;};

Program Of Class   With Single Object  

#<iostream.h>class reactangle{private :int a, b;public :void set_values(int,int);int area(){return(a*b);}};void rectangle::set_values(int a,int b){x=a;y=b;}int main(){rectangle rect;rect.set_values(3,4);

Page 33: C++ Total Concepts

cout<<"area"<<rect.area();return0;}

Output : area 12

A Program Of Class With Two Objects

 

#<iostream.h>class reactangle{int a, b; // private by defaultpublic :void set_values(int,int);int area(){return(a*b);}};void rectangle::set_values(int a,int b){x=a;y=b;}int main(){rectangle rect,rectb;rect.set_values(3,4);rect.set_value(5,7)cout<<"rect area"<<rect.area();cout<<"rectb area"<<rectb.area();return0;}

Output : rect area 12               rectb area 35

Page 34: C++ Total Concepts

Inheritance In C++

Inheritance is a mechanism of reusing and extending classes that already exists without modifying them. One of the most powerful features of class is that they can be extend through inheritance. The feature of reusability implements by inheritance. When we drive a class from another class, the new class gets the functionality of the base class plus whatever new feature we want to add. C++ strongly supports the concept of reusability. The mechanism of deriving a new class from an old class is called  Inheritance.Base class is also called Super Class, and derived class is also called Sub Class.

For Example :  A programmer can create a base class named animal and define derived classes as cat, dog, goat etc. Each of these derived classes has all the features of the base class (animals) with additional attributes. cat would have its own defined features, dog would have its own defined features, goat would have its own defined features, etc.

General Syntax Of Inheritance :class derived-class-name : base-class-name{members of class};

Types Of Inheritance In C++

Single Inheritance Multilevel Inheritance Multiple Inheritance Hierarchical Inheritance Hybrid Inheritance

Single Inheritance :This is one in which there is only one derived class and only one base class. In single inheritance there is one super and one sub class. In single inheritance class may inherit from at most one super class. When a class inherits methods and fields directly from only one base class.

Here class A is base class and class B is derived class.Example Of Single Inheritance :

class abc{    public:    int a, b;};class bcd: public abc     // example of simple inheritance

Page 35: C++ Total Concepts

{    public:     int c;}

Multilevel Inheritance :When a class is derived from another derived class then it called Multilevel Inheritance. In multilevel inheritance a class is derived from other class which is already derived. In multilevel inheritance there are more than one base class and derived class.

Here class A is base class class B is middle derived class and class C is a derived class.Syntax For Multilevel Inheritance :

class A {   //block of code};class B: public A{   //block of code};class c: public B{  //block of  code};

Multiple Inheritance :In multiple inheritance a class is derived form more than one base class.

Here class D is derived from class A, class B, class C (base class) and class D is derived class.Syntax For Multiple Inheritance :

class A{//block of  code};class B{

Page 36: C++ Total Concepts

//block of  code};class C{//block of  code};class D : public A, public B, public C{//block of  code};

Hierarchical Inheritance :If there is only one base class and and more than one class is derived from that class then it called Hierarchical Inheritance.

Here class A is base class and class B, class C, class D are derived class. More than one class is derived from only one base class.Syntax For Hierarchical Inheritance :class A{------------------------};class B: public A{------------------------};class C : public A{----------------------};class D : public A{-------------------------};

Hybrid Inheritance :A hybrid inheritance is the combination of two or more inheritance.

A Program For Single Inheritance

Page 37: C++ Total Concepts

#include<iostream.h>Class A{int a,b;public :void getdata()

{cout<<"\n Enter the value of a and b";cin>>a>>b;}void putdata(){cout<<"\n The value of a is :"<<a<<"and b :"<<b;}};class B : public A //class is publicly derived from A{int c,d;public :void intdata(){cout<<"\n Enter the value of c and d :";cin>>c>>d;}void outdata(){cout<<"\n The value of c ;"<<c<<"and d :"<<d;}};void main(){B obj;obj.getdata(); //base class member functionobj.indata(); //derived class member functionobj.putdata();obj.outdata();}

Output : Enter the value of a and b23Enter the value of c and d45The value of a is 2 and b is 3The value of c is 4 and d is 5

Page 38: C++ Total Concepts

A Program Of Hierarchical Inheritance

#include<iostream.h>Class A{int a,b;public :void getdata(){cout<<"\n Enter the value of a and b";cin>>a>>b;}void putdata(){cout<<"\n The value of a is :"<<a "and b is "<<b;}};class B : public A{int c,d;public :void intdata(){cout<<"\n Enter the value of c and d ";cin>>c>>d;}void outdata(){cout<<"\n The value of c"<<c"and d is"<<d;}};class C: public A{int e,f;public :void input(){cout<<"\n Enter the value of e and f";cin>>e;>>f}void output(){

Page 39: C++ Total Concepts

cout<<"\nthe value of e is"<<e"and f is" <<f;}void main(){B obj1C obj2;obj1.getdata(); //member function of class Aobj1.indata(); //member function of class Bobj2.getdata(); //member function of class Aobj2.input(); //member function of class Cobj1.putdata(); //member function of class Aobj1.outdata(); //member function of class Bobj2.output(); //member function of class Aobj2.outdata(); //member function of class C}

Output : Enter the value of a and b34Enter the value of c and d68Enter the value of a and b9 4Enter the value of e and f18the value of a is 3 and b is 4the value of c is 6 and d is 8the value of a is 9 and b is 4the value of e is 1 and f is 8

 Concept Of Polymorphism In C++

Page 40: C++ Total Concepts

    In the word Polymorphism 'Poly' means 'Many'. Polymorphism is one of the features of  oops. It simply means one name many forms. The  concept of polymorphism is implemented using overloaded function and operator. Polymorphism is a mechanism to use a single name with multiple form.

There are two types of polymorphism

Compile Time Polymorphism  (Function Overloading , Operator Overloading) Run time Polymorphism (Virtual Function)

Compile Time Polymorphism :In this form of polymorphism the selection of the function invocation is done on compile time. This is also called early binding or static binding. This can be achieved by two ways :

Function Overloading Operator Overloading

Runtime Polymorphism :If the member function is selected when the program is running then it called Runtime Polymorphism. This is also called late binding or dynamic binding. Runtime Polymorphism achieve the concept of Virtual Function.

Function Overloading :Function overloading means multiple functions of same name with different arguments. C++ allows functions to be overloaded, that is the same function to have more than one definition.

Operator Overloading :Operators are similar to functions they take operands and return a value. For Example : the + operator can be used to add two integers, two reals or two addresses.

Virtual Function :Virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes. It can be used with virtual keyword. Virtual member functions are resolved during run-time. This mechanism is known as dynamic binding.The non-virtual member functions are resolved at compile time. This mechanism is called static binding. 

Page 41: C++ Total Concepts

Program Of Function Overloading

#include<stdio.h>void myfunction(int a){cout<<"a is "<<a;//overload myfunctionvoid myfunction(int a, int b){cout<<"a is"<<a;cout<<"b is"<<b;}//overload myfunction againvoid myfunction(int a, double b){cout<<"a is"<<a;cout<<"b is"<<b;}void main(){myfunction(12); //calls myfunction(int)myfunction(10,34) //calls myfunction(int, int)myfunction(67,123.45) //calls myfunction(int, double)}

Output : a is 12a is 10b is 34a is 67b is 123.45

Program Of Swapping in C++

#include<stdio.h>#include<conio.h>void main(){int a, b ;

Page 42: C++ Total Concepts

cout<<"\n Enter two values";cin>>a>>b;cout<<"value of a =" <<a<< "and b ="<<b;a=a+b;b=a-b;a=a-b;cout<<"\n value after swaping";cout<"\n value of a="<<<a;cout<<"\nvalue of b="<<b;}

output : Enter two values12 23value of a =10 and b =23value after swappingvalue of a=23value of b=12

A program to input any number and write all the digits in words

#include<stdio.h>#include<conio.h>void main(){int num,a;cout<<"\n Enter the number";cin>>num;while(num!=0){a=num%10;num=num/10;switch(a){case 1 :cout<<"one";break;case 2 :cout<<"two";break;case 3

Page 43: C++ Total Concepts

:cout<<"three";break;case 4 :cout<<"four";break;case 5 :cout<<"five";break;case 6 :cout<<"six";break;case 7 :cout<<"seven";break;case 8 :cout<<"eight";break;case 9 :cout<<"nine";break;case 10 :cout<<"zero";break;}}}

Output : 396three nine six

Program To Check Whether The Number Is Prime Or Not Using C++

#include<stdio.h>#include<conio.h>void main(){int num,a=1;cout<<"\n Enter the number";cin>>num;for(int i=2;i<num/2;i++){if(num%i==0)p=p*0;

elsep=p*1;}}if(p!=0)

Page 44: C++ Total Concepts

cout<<"\n number is prome";elsecout<<"\n number is not prime";}

Output : Enter the number6number is not prime

Program Of Fibonacci Series In C++

#include<stdio.h>#include<conio.h>void main(){int sum,f1,f2,n;f1=o;f2=1;cout<<"\n Enter the range";cout<<f1<<"/t"<<f2;cout<"\n< the series is";for(int i=2;i<=n;i++){sum=f1+f2;cout<< fib<<"/t";f1=f2;f2=sum;}}

output : Enter the range120 1 1 2 3 5 8 13 21 34 55 89

A Simple Array Example Using C++

#include<stdio.h>#include<conio.h>int main(){

Page 45: C++ Total Concepts

int myarray[5];int i;for(i=0;i<5;i++){cout<<"Enter the value for array"["<<i<<"];cin>>myarray[i];}for(i=0;i<5;i++)cout<<i<<" : "myarray[i]<<"\n;"return 0;}

output : Enter the value of array[0] 3Enter the value of array[1] 6Enter the value of array[2] 9Enter the value of array[3] 12Enter the value of array[4] 150 :31:62:93:124:15

Program Of Pointer In C++

#include<iostream.h>int main(){int firstval=5, secondval=15;int *p1,*p2;p1=&firstval; //p1=address of firstvalp2=&secondval; //p2=address of secondval*p1=10; //value pointed y p1=10*p2=*p1; //value pointed y p2=value pointed y p1p1=p2; //value of pointer is copied

Page 46: C++ Total Concepts

*p1=20; //value pointed by p1=20cout<<"firstval is"<<firstval;cout<<"secondval is"<<secondval;return 0;}

output :first value is 10second value is 20

Program To Calculate Area Of Rectangle, Circle, Triangle

#include<stdio.h>void main();void area_circle();void area_rect();void area_tri();void main(){int option;{domenu();cin>>option;do{menu();cin>>option;switch(option){case 1:area_circle();break;case 2:area_rect();break;case 3:area_tri();break;}}while(option>3);}void menu()

Page 47: C++ Total Concepts

{cout<<"\n Menu";cout<<"\n 1: Area of circle";cout<<"\n 2: Area of rectangle";cout<<"\n 3: Area of trangle";cout<<"\n 4 or greater :Exit";cout<<"\n Eneter your choice";}void area_circle(){int r;cout<<"\n Enter radius";cin>>r;float area=3.14*r*r/4;cout<<"\n area of circle"<<area;}void area_rect(){int a,b;cout<<"\n enter sides";cin>>a>>b;int area=a*b;cout<<"\narea of rectangle"<<area;}void area_triangle(){float s,a,b,c;cout<<"\n enter sides";cin>>a>>b>>c;s=(a+b+c)/2float area=s*(s-a)*(s-b)*(s-c);cout<<"\n area of triangle"<<area;}

Output : Menu1 : Area of circle2 : Area of rectangle3 : Area triangle4 or greater ExitEnter your choice1enter radius

Page 48: C++ Total Concepts

4Area of circle12.56

Program To Convert An Input Lower Case In Upper Case

#include<iostream.h>void main(){char str[20],*s;cout<<"\n enter the string";cin>>str;s=str;while(*s!='\0'){if(*s>=97&&*s<=122)*s=*s-32;*s++}cout<<"\n string is upper case"<<str;}

output :Enter the stringcomputerstring in upperCOMPUTER

Demonstration Of Private And Public in C++

#include<stdio.h>class demo{private :int x,y;

Page 49: C++ Total Concepts

public :int a,b;void getdata();void putdata();};void demo::getdata(){cout<<"\n Emnter the value of x and y";cin>>x>>y;cout<<"\n Enter the value of a and b";cin>>a>>b;}void demo::putdata(){cout<<"\n Enter the value of x amd y";cout<<"\n Enter the value of a and b";}void main(){demo d;d.getdata();cout<<"\n the entered values are";d.putdata();d.a=10;d.b=20;cout<<"\n The value after moderation are";d.putdata();}

Output : Enter value of x and y23 79Enter value of a and b200100The entered values arethe value of x is 23 and y is 79the value of a is 200 and b is 100he value after moderationthe value of x is 23 and y is 79the value of a is 10 and b is 20

Page 50: C++ Total Concepts

Program For Finding Largest Number in C++

#include<stdio.h>class num{int a,b,c;public :void input(void);void largest(void);void smallest(void);};void num::inputdata(void){cout<<"Input value of a ";cin>>a;cout<<"Input value of b";cin>>b;cout<<"input value of c";cin>>c;}void number :: largest(void){if(a>b){if(a>c)cout<"\n largest value"<<<a;elsecout<<"\n largest value"<<c;}else{if(b>c)cout<<"\n largest value"<<b;elsecout<<"\n largest value"<<c;}}void num::smallest(void){if(a<b){if(a<c){cout<<"\n smallest number"<<a;elsecout<<"\n smallest number"<<c;}else{if(b<c)cout<<"\n smallest numeber"<<b;

Page 51: C++ Total Concepts

elsecout<<"\n smallest number" <<c;}}int main(){num n;n.input();n.largest();n.smallest();return 0;}

output : input value of a=15input value of b=34input value of c=30largest value is 34smallest value is 15

Program Of Single Inheritance

#include<stdio.h>class A{int a1,a2;public :void getdata(){cout<<"\n Enter value of a1 and a2";cin>>a1>>a2;}void putdata(){cout<<"\n value of a1 is" <<a1"and a2 is"<<a2;}

};class B: public A //class B is publicly derived by class A{int b1,b2;

Page 52: C++ Total Concepts

public :void indata(){cout<<"\n Enter the value of b1 nad b2";cin>>b1>>b2;}};void main(){B b;b.getdata(); //base class member functionb.indata(); //derived class member functionb.putdata();b.outdata();}

output : enter value of a1 and a223enter  value of b1 and b245the value of a1 is 2 and a2 is 3the value of b1 is 4 and b2 is 5

Program For Multilevel Inheritance Example Using C++

#include<stdio.h>class A{int a1,a2;public :void getdata(){cout<<"\n Enter value of a1 and a2";cin>>a1>>a2;}void putdata(){cout<<"\n value of a1 is" <<a1"and a2 is"<<a2;}

Page 53: C++ Total Concepts

};class B: public A //class B is publicly derived by class A{int b1,b2;public :void indata(){cout<<"\n Enter the value of b1 nad b2";cin>>b1>>b2;}void outdata(){cout<<"\n the value of b1 is" <<b1 "and b2 is:<<b2;}};class C: public B{int c1,c2;publicvoid input(){cout<<"\n enter the value of c1 and c2";cin>>c1>>c2;}void output(){cout<<"\nvalue of c1 is"<<c1"and c2 is"<<c2;}};void main(){C objobj.getdata(); //member function of class Aobj.indata(); //member function of class Bobj.input(); //member function of class Cobj.putdata(); //member function of class Aobj.outdata(); //member function of class Bobj.output(); //member function of class C}

output :Enter value of a1

Page 54: C++ Total Concepts

and a234Enter value of b2 and b267Enter value of c1 and c289the value of a1 is 3 and a2 is  4the value of b1 is 6 and b2 is 7the value of c1 is 8 and c2 is 9

Program For Multiple Inheritance Example Using C++

#include<stdio.h>class A{int a1,a2;public :void getdata(){cout<<"\n Enter value of a1 and a2";cin>>a1>>a2;}void putdata(){cout<<"\n value of a1 is" <<a1"and a2 is"<<a2;}};class B{int b1,b2;public :void indata(){cout<<"\n Enter the value of b1 nad b2";cin>>b1>>b2;}void outdata(){cout<<"\n the value of b1 is" <<b1 "and b2 is:<<b2;}};class C: public A,public B

Page 55: C++ Total Concepts

{int c1,c2;publicvoid input(){cout<<"\n enter the value of c1 and c2";cin>>c1>>c2;}void output(){cout<<"\nvalue of c1 is"<<c1"and c2 is"<<c2;}};void main(){C cc.getdata(); //member function of class Ac.indata(); //member function of class Bc.input(); //member function of class Cc.putdata(); //member function of class Ac.outdata(); //member function of class Bc.output(); //member function of class C}

Output : Enter the value of a1 and a25 4Enter the value of b1 and b287enter the value of c1 and c193The value of a1 is 5 and a2 is 4The value of b1 is 8 and b2 is 7The value of c1 is 9 and c2 is 3

Page 56: C++ Total Concepts