Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Programming.

Similar presentations


Presentation on theme: "C++ Programming."— Presentation transcript:

1 C++ Programming

2 What is C++ It is an Object Oriented Programming Programming language . C, Pascal, Basic are based on pop ( procedure oriented programming ) approach. POP concept follow the top-down design approach. In this approach we have single program normally main() function which is divided into small piece called procedure or function.

3 OOP(object Oriented programing)
OOP:- Object Oriented Programming. In pop the emphasis is on the function rather than data and data is also not secured in this approach. In oop approach eliminates this weakness of pop approach by combining the data and function that work on it into a single unit called ‘class’, so data is secured from the outside world because data can be changed by associated function only.

4 Variable types Local variable
Local variables are declared within the body of a function, and can only be used within that function. Static variable Another class of local variable is the static type. It is specified by the keyword static in the variable declaration. The most striking difference from a non-static local variable is, a static variable is not destroyed on exit from the function. Global variable A global variable declaration looks normal, but is located outside any of the program's functions. So it is accessible to all functions.

5 An example int global = 10; //global variable int func (int x) { static int stat_var; //static local variable int temp; //(normal) local variable int name[50]; //(normal) local variable …… }

6 Variable Definition vs Declaration
Tell the compiler about the variable: its type and name, as well as allocated a memory cell for the variable Declaration Describe information ``about'' the variable, doesn’t allocate memory cell for the variable

7 lvalue:- It is the name of a variable.
Eg:- int a=25; rvalue lvalue What is Control Statement? C++ support different type of control statement.

8 If statement:- Syntax:-
Selection or conditional statement if satement if-else statement switch statement nested -if satement Iterative or Looping statement For loop While loop Do-while loop Nested for statement Breaking Statement Break statemnt Continue statement goto statement Exit statement If statement:- Syntax:- If(expression) { (body of if) Statements; }

9 #include<iostream.h>
#include<conio.h> void main() { clrscr(); cout<<”Enter a number”; cin>>n; if(n%2==0) cout<<”the number”<<n<<”is even”<<endl; } getch();

10 If-else statement #include<iostream.h> #include<conio.h>
void main() { clrscr(); cout<<”Enter a number”; cin>>n; if(n%2==0) cout<<”the number”<<n<<”is even”<<endl; } Else cout<<”the number”<<n<<”is odd”<<endl; getch();}

11 Switch Statement:-Switch is a alternative for if else condition.
Syntax:- Switch(expression) case exp1:First case body; ``Break; case exp2:Second case body;Break; caseexp n:nth case body:break; default:default case body; } Eg:- #include<iostream.h> #include<conio.h> void main() { clrscr(); int income=5000; switch (income)

12 Nested if statement:- case 3000:
cout<<”the tax is:”<<income*0.3/100<<endl; break; case 4000: cout<<”the tax is:”<<income*0.4/100<<endl; case 5000: cout<<”the tax is:”<<income*0.5/100<<endl; default: cout<<”no tax”<<endl; } getch();} Nested if statement:- #include<iostream.h> #include<conio.h> void main() { clrscr();

13 int age=25; if(age>20) { cout<<”you are eligible to vote”<<endl; if(age<=25) Cout<<”your age is perfect to vote”<<endl; } else Cout<<”you are not eligible to vote”<<endl; getch();

14 Nested if else #include<iostream.h> #include<conio.h>
void main() { clrscr(); int age=25; if(age>20) { cout<<”you are eligible to vote”<<endl; if(age<=25) Cout<<”your age is perfect to vote”<<endl; }

15 else { Cout<<”you are not eligible to vote”<<endl; } getch();

16 Lecture no 2 Define Oop concept:-
In oop approach eliminate this weakness of pop by combine the data and the function that work on it into a single unit called as class so the data is from the outside world because data can be change by associate function only oop is implemented on the real world entities called object that have some characteristics and behaviour.

17 State different between c and c++
C (POP) C++ (OOP) Procedural Oriented Programming Object Oriented Programming Data is not secure Data is secure Data and Function are not combine together Data and function are combined together This is good for scientific application development This is good for object oriented real time website development It does not support feature of oop An feature of pop may be present in oop We can't define abstract data type We can define abstract data type Many function can access same data Object communicate with each other by message passing

18 History of c++:- C++ is a object oriented language developed by BjarneStroustrup at AT and T Bell laboratories in Simula is 1st Object Oriented language. It was the during strct of feature simula 67 language to c therefore strustrop have giving the name was change to CPP the name derieved for post increment operator of C which is used to increment value of operand by one therefore, we can say that C++ is an incremental development of C an existence to existing of syntax. CPP simple program:- #include<iostrem.h> #include<conio.h> Void main() { Cout<<”Hello Mr.Umakant”<<endl; Getch(); }

19 iostream :- Combination of istream and ostrem to handle bidirectional operations on a single stream. In above example cout is used for displaying the message or value.<< this is the operator which concatenates string or value. #include<iostrem.h> #include<conio.h> Void main() { Char nm[50]; Cout<<”Enter your name:”<<endl; Getch(); } Cin:-Cin is used for taking input of console.

20 Lecture No 3 #include<iostrem.h> #include<conio.h>
While Loop:- #include<iostrem.h> #include<conio.h> Void main() { Inti=1; While (i<=10) Cout<<”i”<<endl; I++; } Getch();

21 Do- While Loop:- #include<iostream.h> #include<conio.h>
Void main() { Inti=1; Clrscr(); Do Cout<<i<<endl; I++; } While(i<=10); Getch(); Note:- There is difference between while and do while loop is.

22 #include<iostream.h> #include<conio.h> Void main() {
In while loop first check the condition then execute the statement, but in do while loop first execute the statement atleast once then check the condition. For Loop:- for loop is a combined pattern of while or do-while.. Eg:- #include<iostream.h> #include<conio.h> Void main() { Clrscr(); For(inti=0;i<=10;i++) Cout<<”hello Sheryl how are u”<<endl; } Getch();

23 Nested for statement:-
#include<iostream.h> #include<conio.h> Void main() { Clrscr(); For(inti=0;i<=10;i++) For(int j=0;j<i;j++) Cout<<”*”; } Cout<<”\n”; getch();

24 Continue:- Continue is used for swaping the current iteration. Eg:-
#include<iostream.h> #include<conio.h> Void main() { Clrscr(); For(inti=0;i<=10;i++) If(i==4) Continue; } Cout<<i<<endl; Getch();

25 Goto:- A goto statement provides an unconditional jump from the goto to labelled statement in the same function. Note:- use of goto is highly discouraged because it makes difficult to trace the control flow of program hard to understand and modify. Eg:- Void main() { Int a=10; LOOP:do If(a==15) A=a+1; Goto LOOP; } Cout<<”value of a:”<<a<<endl;

26 Exit:- } While(a<20); Getch();
Exit terminates the calling process immediately. Any open file descriptor belonging to the process are closed and any children of the process are inherited by the process. #include<stdlib.h> #include<iostram.h> #include<conio.h> Void main() { Cout<<”start of the program......”<<endl; Cout<<”end of the program......”<<endl; Exit(0);

27 Array:- array is the collection of single data item which may be integer type, char type, float type, user defined such as structure. Type of an array:- Single Dimensional:- it is collection of similar data item. It also called sometime list. Single dimensional array are simplest form of array. Multi dimensional array:- it is also collection of similar data item where dataitem is a simple case of multi dimensional array there each element array is single dimensional array.

28 Initialization of an array:-
1. Int x[2] x[0]=10; x[1]=20; 2. Int x[2]={10,20} #include<iostram.h> #include<conio.h> Void main() { Intx[5]={10,20,30,40,50}; Inti; Clrscr(); Cout<<”\n iteration array element using loop”<<endl; For (i=0;i<5;i++) Cout<<”the element of array are:”<<x[i]<<endl; } Getch();

29 Different between Array &structure
Array is a collection of similar data items Structure can have different data item Array name is not used as data type Structure name is used to define the variable of that type Array element can be accessed by their position in the array Structure element has different name Array has finite no of element Structure also have finite no of elements Memory is allocated at the time of declaration Memory is not allocated when the structure is declared, but when the structure variable is declared.

30 How to access structure element?
Dot operator:- The structure variable cannot read and write the value in single command .once structure variable is defined its members can be accessed by using dot operator. Initialization of structure:- there are 2 types of initialization of structure. Eg:-bdate.day=1; Bdate.month=1; Bdate.year=2015; or date bdate= {1,1,2015}; Eg:- #include<iostram.h> #include<conio.h> #include<string.h> Struct date

31 { Intdt; Char month[5]; Int year; Char day[5]; }DOB; Void main() DOB.dt=25; Strcpy(DOB.month,”jan”); DOB.year=1995; Strcpy(DOB.day,”wed”); Clrscr(); Cout<<”the dob is:”<<DOB.dt<<” ”<<DOB.month<<” ”<<DOB.year<< “ ”<<DOB.day<<endl; Getch(); }

32 Enumerated Data Type:- Enumdatatype consist of a set of named values
Enumerated Data Type:- Enumdatatype consist of a set of named values. These values can be used in indexing expressions. The ides behind enumerated datatype is to create Enumerated datatype in C++:- new datatype that can take on only a restricted range of values. #include<iostream.h> #include<conio.h> Void main() { Enumfruits{orange, mango,apple}; Fruits myfruit; Clrscr(); Int I; Cout<<”please enter the fruit of your choice (0 to 2):” Cin>>I; Switch(i)

33 Case orange; Cout<<”your fruit is orange”; Break; Case mango; Cout<<”your fruit is mango”; Case apple; Cout<<”your fruit is apple; } Getch(); String functions in c++:- String classes:- strings are the objects that represents sequence of characters.the standard string classes providesupport for such supports with an interface similar to that of a

34 standard container of bytes, but adding features specifically designed to operate with strings of single byte characters. Eg:- #include<iostream.h> #include<conio.h> Void main() { Char str[100]; Cout<<”enter a string:”; Cin>>str; Cout<<”you entered:””<<str<<endl; Cout<<”\n enter another string:”; Cout<<”you entered:”<<str<<endl; Getch(); }

35 Size:- returns length of a string
Size:- returns length of a string. This is the number of actual bytes that confirm the contents of the string we can find length of the string. Strlen:- it will just return the length of a string. Function:- Function is a block of code that perform particular task according to user input. It of two types: 1. Parameterized function 2. Non Parameterized function Parameterized function:- #include<conio.h> #include<iostream.h> void add(int a,int b) { cout<<"Sum of two number is :"<<(a+b)<<endl; } void main()

36 clrscr(); add(10,20); getch(); } Non parameterized function:- #include<conio.h> #include<iostream.h> void main() { void show() {cout<<"Hello ! i am from Non parameterized :"<<endl;

37 CLASS:- Class is a Template/Blueprint for an object. Object is an instance of a class means how many object we are created that many instance we will create. Ex. #include<iostream.h> #include<conio.h> #include<string.h> class student { private: int age; char add[40]; char name[40]; public: void stdetails(int a, char nm[40],char address[40])

38 age=a; strcpy(add,address); strcpy(name,nm); cout<<"Name of the student is : "<<name<<"\nAge of the student is :"<<age<<endl; cout<<"Address of the student is :"<<add<<endl; } }; void main() { clrscr(); student st; st.stdetails(21,"Dharmendra","Virar"); st.stdetails(26,"veerendra","Virar"); getch();

39 ACCESS SPECIFIER:- There are three type of access specifier in the c++: 1. Private 2. Public 3. Protected Private Access Specifier: If we declare any variable a private specifier then it can be access only in that class where it is declared. Ex: Private : Int age; Char name[100]; Public Access Specifier:- If we declare any variable as a public specifier then it can be access in that class and also outside of that class where it is declared.

40 Ex: Public : Int age; Char name[100]; Protected Access Specifier:- If we declare any variable a protected specifier then it can be accessable only in that class and also in it sub class where it is declared. Protected :- Scope Resolution Operator: If we declare any variable inside the class & we want to access that variable outside the class then we use scope resolution operator. Syntax: return type class_name :: method_name;

41 Memory Allocation: Memory in c++ divided in to two part: The Stack: All variable declare inside the function will take up memory from the stack. The Heap: This is unused memory of the program and can be used to allocate the memory dynamically when runs. We can allocate the memory at runtime with in the heap for the variable of a given type using a social operator in c++ which return the address of the space allocated. This operator is called new operator.If we are not in need of dynamically allocated memory anymore previously allocated by new operator. The New & Delete Operator: This is the following generic syntax to use new operator to allocate memory dynamically for any data type, new data type .

42 Ex: #include<conio.h> #include<iostream.h> #include<string.h> void main() { double* pvalue = null; pvalue=new double; clrscr(); cout<<"Value of pvalue is : "<<*pvalue<<endl; delete pvalue; getch(); } Static Data Member: We can define class member static using static keyword. When we declare a member of a class as static it means matter how many object of the class are created, there is only one copy of the static member. A static

43 member is shared by all object of the class
member is shared by all object of the class.All static data is initialized to zero when the first object is created, if no other initialization is present Ex: #include<conio.h> #include<iostream.h> void counter() { static int count =0; cout<<count<<endl; } void main() clrscr(); for(int i=0;i<5;i++) cout<<i<<endl; getch();

44 Friend Function: A c++ friend function are special function which can access the private member of the class. They are considered to be a lope hole in the Oop concept. But logical use of them can make them useful in certain class for instance.When it is not possible to implement some function, without making private accessible in them. This situation arrived mostly in case of operator overloading. Fiend function has following property: Friend of the class can be member of the some class. Friend of one class can be friend of other class or all the classes in the program, such a friend is known as global friend. Friend can access the private and protected member of class in which they are declared to be friend but they can use the member for a specific object.

45 Friend are non member hence don’t get this pointer.
Friend can be friend more than one class, hence they can use for message passing between the classes. Friend can be declared any where [in public, private, protected section] in the class. Ex: #include<conio.h> #include<iostream.h> class base { int val1,val2; public : void get() cout<<"Enter two values :"; cin>>val1>>val2; } friend float mean(base ob);

46 }; float mean(base ob) { return float(ob.val1+ob.val2)/2; } void main() clrscr(); base obj; obj.get(); cout<<"Mean value is :"<<mean(obj)<<endl; getch(); Constructor: Constructor is just like method having same name as a class name but having no return type.

47 Ex: #include<conio.h> #include<iostream.h> class calculater { public : int a,b; float x,y; calculate(int a,int b) a=a; b=b; cout<<"Sum of two number is :"<<(a+b)<<endl; } calculate(int x, int y) x=x;

48 y=y; cout<<"Multiplication of two number is :"<<(x*y)<<endl; } ~ calculate(); { cout<<"Hello word :“ }; void main() clrscr(); calculate(10,20); calculate(20,30); getch();

49 Constructor Type: Ex: #include<conio.h> #include<iostream.h> Class calculate { Public : Calculate() Cout<<”Hello ! I am from default :”<<endl; } }; Void main() Clrscr(); Calculate cal(); Getch();

50 Default : Ex: #include<conio.h> #include<iostream.h> Class calculate { Public : Calculate(int x=20) Cout<<”Hello ! I am from default :”<<x<<endl; } }; Void main() Clrscr(); Calculate cal(50);// Calculate cal(); Getch();

51 Copy : Ex: #include<conio.h> #include<iostream.h>
#include<string.h> class student { private : char name[10]; int standard; public : char division[10]; int rollno; char result[10]; student(int std,char r) standard=std; result=r; } void student (int roll,char n[10],char r[10]) rollno=roll;

52 strcpy(name n); strcpy(result r); } void showresult() { cout<<"standard :"<<standard<<endl; cout<<"divisio :"<<division<<endl; cout<<"name :"<<name<<endl; cout<<"rollno :"<<rollno<<endl; cout<<"result :"<<result<<endl; }; void main() clrscr(); student std1(12,'D'); std1.student("Krishna",1,"Pass");std1.showresult(); getch();

53 Constructor Overloading:
Multiple constructors having same name different parameter is known as constructor overloading. Ex: #include<conio.h> #include<iostream.h> #include<string.h> class student { public : int rollno; char div[10]; char name[10]; int marks; student() rollno=1; div="A"; strcpy(name,"Dharmendra"); marks=33; }

54 student(int m) { rollno=2; div="B"; strcpy(name, "Dharmendra"); marks = m; } Student (int r, char d, char n[10], int m) rollno =r; div = d; strcpy(name,n); marks=m; void display() cout<<"Roll No. :"<<rollno<<endl; cout<<"Division :"<<div<<endl; cout<<"Name :"<<name<<endl; cout<<"Marks :"<<marks<<endl; };

55 C++ Inline Function: void main() {
student std1,std2(78),std3(67,'D',"DHaram",89); clrscr(); std1.display(); std2.display(); std3.display(); getch(); } Method Overloading: Multiple method have same name, different parameter is known as method overloading. C++ Inline Function: It is powerful concept that is commonly used with class. If a function is inline the compiler places a copy of the code of that function at each point where the function is called at compile time. To inline a function, place the keyword inline before any function name & define the function before any call are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line.

56 Ex: #include<conio.h> #include<iostream.h> inline float mul(float x, float y) { return (x*y); } inline double div(double x, double y) return (x/y); void main() clrscr(); float a=12.345; float b=9.85; cout<<”Product :”<<mul(a,b)<<endl; cout<<”Division :”<<div(a,b)<<endl; getch();

57 Creating object Array:
Ex: #include<conio.h> #include<iostream.h> class objArr { private : int x; int y; public : void add(int x, int y) x=x; y=y; cout<<"Sum of two number is :"<<(x+y)<<endl; } }; void main() clrscr(); objArr ob[4];

58 Memory in your C++ program is divided into two parts:
ob[0].add(10,20); ob[1].add(20,430); ob[2].add(70,30); ob[3].add(40,20); getch(); } Memory in your C++ program is divided into two parts: The stack: All variables declared inside the function will take up memory from the stack. The heap: This is unused memory of the program and can be used to allocate the memory dynamically when program runs. we can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This operator is called new operator. If we are not in need of dynamically allocated memory anymore, we can use delete operator, which de-allocates memory previously allocated by new operator. The new and delete operators: There is following generic syntax to use new operator to allocate memory dynamically for any data-type. new data-type;

59 double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable The memory may not have been allocated successfully, if the free store had been used up. So it is good practice to check if new operator is returning NULL pointer and take appropriate action as below: double* pvalue = NULL; if( !(pvalue = new double )) { cout << "Error: out of memory." <<endl; exit(1); } The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. The main advantage of new over malloc() is that new doesn't just allocate memory, it constructs objects which is prime purpose of C++. At any point, when you feel a variable that has been dynamically allocated is not anymore required, you can free up the memory that it

60 occupies in the free store with the delete operator as follows:
delete pvalue; // Release memory pointed to by pvalue Let us put above concepts and form the following example to show how new and delete work: #include <iostream> using namespace std; int main () { double* pvalue = NULL; // Pointer initialized with null pvalue = new double; // Request memory for the variable *pvalue = ; // Store value at allocated address cout << "Value of pvalue : " << *pvalue << endl; delete pvalue; // free up the memory. return 0; }

61 If we compile and run above code, this would produce the following result:
Value of pvalue : 29495 Dynamic Memory Allocation for Arrays: Consider you want to allocate memory for an array of characters, i.e., string of 20 characters. Using the same syntax what we have used above we can allocate memory dynamically as shown below. char* pvalue = NULL; // Pointer initialized with null pvalue = new char[20]; // Request memory for the variable To remove the array that we have just created the statement would look like this: delete [] pvalue; // Delete array pointed to by pvalue Following the similar generic syntax of new operator, you can allocat for a multi-dimensional array as follows: double** pvalue = NULL; // Pointer initialized with null pvalue = new double [3][4]; // Allocate memory for a 3x4 array However, the syntax to release the memory for multi-dimensional array will still remain same as above:

62 Dynamic Memory Allocation for Objects:
Objects are no different from simple data types. For example, consider the following code where we are going to use an array of objects to clarify the concept: #include <iostream> using namespace std;  class Box { public: Box() { cout << "Constructor called!" <<endl; } ~Box() { cout << "Destructor called!" <<endl; };  int main( ) Box* myBoxArray = new Box[4];   delete [] myBoxArray; // Delete array   return 0;

63 If you were to allocate an array of four Box objects, the Simple constructor would be called four times and similarly while deleting these objects, destructor will also be called same number of times. If we compile and run above code, this would produce the following result: Constructor called! Destructor called! static  We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present.

64 Friend Functions A C++ friend functions are special functions which can access the private members of a class. They are considered to be a loophole in the Object Oriented Programming concepts, but logical use of them can make them useful in certain cases. For instance: when it is not possible to implement some function, without making private members accessible in them. This situation arises mostly in case of operator overloading. Friend functions have the following properties: 1) Friend of the class can be member of some other class. 2) Friend of one class can be friend of another class or all the classes in one program, such a friend is known as GLOBAL FRIEND. 3) Friend can access the private or protected members of the class in which they are declared to be friend, but they can use the members for a specific object. 4) Friends are non-members hence do not get “this” pointer. 5) Friends, can be friend of more than one class, hence they can be used for message passing between the classes. 6) Friend can be declared anywhere (in public, protected or private section) in the class.

65 #include<iostream.h>
#include<conio.h> class base { int val1,val2; public: void get() cout<<"Enter two values:"; cin>>val1>>val2; } friend float mean(base ob); }; float mean(base ob) return float(ob.val1+ob.val2)/2; void main() clrscr(); base obj; obj.get(); cout<<"\n Mean value is : "<<mean(obj); getch();

66 C++ inline function: is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time. To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line. Operator Overloading Overloaded operator is used to perform operation on user-defined data type. For example '+' operator can be overloaded to perform addition on various data types, like for Integer, String(concatenation) etc. .Operator that are not overloaded are follows

67 Rules of Operator Overloading
Following are some restrictions to be kept in mind while implementing operator overloading. Precedence and Associativity of an operator cannot be changed. Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary remains binary etc. No new operators can be created, only existing operators can be overloaded. Cannot redefine the meaning of a procedure. we cannot change how integers are added. Unary operators overloading in C++ The unary operators operate on a single operand and following are the examples of Unary operators: The increment (++) and decrement (--) operators The unary minus (-) operator. The logical not (!) operator. The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well like obj++ or obj--.

68 Inheritance: One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time. When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

69 Type of Inheritance: Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from one base class. Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits from multiple base classes. Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple subclasses inherit from one base class. Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class for other classes. Hybrid Inheritance: The inheritance hierarchy that reflects any legal combination of other four types of inheritance.

70 Pictorial representation of Inheritance

71 Example of Single Inheritance
#include<iostream.h> #include<conio.h> class A { int a;int b; public: void cal(int x,int y) a=x; b=y; cout<<"the sum of two number is :"<<(x+y)<<endl; } }; cont..

72 class singleDemo :public A
{ int c,d; public: void show(int m,int n) c=m; d=n; cout<<"the multiplication of two number is :"<<(m*n)<<endl; } }; void main() singleDemo sd; clrscr(); sd.cal(10,20); sd.show(10,20); getch();

73 Example of multiple inheritance
#include<iostream.h> #include<conio.h> //multiple inheritance class A { int a; public: void getdata_A() a=10; cout<<"\na="<<a; } }; class B int b; void getdata_B() b=20; cout<<"\nb="<<b;

74 class C:public B,public A
{ int c; public: void getdata_C() c=30; cout<<"\nc="<<c; } }; void main() //create object of class B C c; clrscr(); c.getdata_B(); //b.getdata_A(); c.getdata_C(); c.getdata_A(); getch();

75 C++ Type Conversions By Sripriya R | on August 13, 2006 | Comments: What is type conversion It is the process of converting one type into another. In other words converting an expression of a given type into another is called type casting. How to achieve this There are two ways of achieving the type conversion namely:Automatic Conversion otherwise called as Implicit Conversion Type casting otherwise called as Explicit Conversion Let us see each of these in detail:Automatic Conversion otherwise called as Implicit Conversion This is not done by any conversions or operators. In other words the value gets automatically converted to the specific type to which it is assigned. Let us see this with an example: #include <iostream> #include<conio.h> void main() { short x=6000; int y; y=x; }

76 In the above example the data type short namely variable x is converted to int and is assigned to the integer variable y. So as above it is possible to convert short to int, int to float and so on. Type casting otherwise called as Explicit Conversion Explicit conversion can be done using type cast operator and the general syntax for doing this is : datatype (expression); Here in the above datatype is the type which the programmer wants the expression to gets changed as. In C++ the type casting can be done in either of the two ways mentioned below namely: C-style casting C++-style casting The C-style casting takes the synatx as (type) expression This can also be used in C++. language namely C++-style casting is as below namely: type (expression) example: #include <iostream> Void main()

77 void main() { int a; float b,c; cout << "Enter the value of a:"; cin >> a; cout << "Enter the value of b:"; cin >> b; c = float(a)+b; cout << "The value of c is:" << c; } What Are Pointers?  A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is: type *var-name;

78 Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration: int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch // pointer to character The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. Using Pointers in C++: There are few important operations, which we will do with the pointers very frequently. (a) we define a pointer  

79 variables (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations: #include <iostream> void main () { int var = 20; // actual variable declaration. int *ip; // pointer variable   ip = &var; // store address of var in pointer variable   cout << "Value of var variable: "; cout << var << endl;   // print the address stored in ip pointer variable cout << "Address stored in ip variable: "; cout << ip << endl;

80 cout << "Value of *ip variable: ";
cout << *ip << endl; getch();; } When the above code is compiled and executed, it produces result something as follows: Value of var variable: 20 Address stored in ip variable: 0xbfc601ac Value of *ip variable: 20 C++ Pointers in Detail: Pointers have many but easy concepts and they are very important to C++ programming. There are following few important pointer concepts which should be clear to a C++ programmer:

81 C++null variable Concept Description C++ pointer arithmetic
C++ supports null pointer, which is a constant with a value of zero defined in several standard libraries. C++ pointer arithmetic C++ pointer vs variable There is a close relationship between pointers and arrays. Let us check how? C++ array of pointer You can define arrays to hold a number of pointers. C++ pointer to pointer C++ allows you to have pointer on a pointer and so on. Passing function to pointer Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.

82 POINTER TO OBJECT: A pointer to a C++ class is done exactly the same way as a pointer to a structure and to access members of a pointer to a class you use the member access operator -> operator, just as you do with pointers to structures. Also as with all pointers, you must initialize the pointer before using it. Let us try the following example to understand the concept of pointer to a class: #include <iostream> #include<conio.h>  class Box { public: Box(double l=2.0, double b=2.0, double h=2.0) cout <<"Constructor called." << endl; length = l; breadth = b; height = h; } double Volume() return length * breadth * height;

83 } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box };  int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 Box *ptrBox; // Declare pointer to a class.   // Save the address of first object ptrBox = &Box1; // Now try to access a member using member access operator cout << "Volume of Box1: " << ptrBox->Volume() << endl; ptrBox = &Box2; cout << "Volume of Box2: " << ptrBox->Volume() << endl; getch();

84 When the above code is compiled and executed, it produces the following result:
Constructor called. Volume of Box1: 5.94 Volume of Box2: 102 C++ Virtual Function If there are member functions with same name in base class and derived class, virtual functions gives programmer capability to call member function of different class by a same function call depending upon different context #include <iostream> #include<conio.h> class B { public: void display() { cout<<"Content of base class.\n"; } }; class D : public B { cout<<"Content of derived class.\n"; }

85 };  int main() { B *b; D d; b->display();   b = &d; /* Address of object d in pointer variable */ return 0; } Note: An object(either normal or pointer) of derived class is type compatible with pointer to base class. So, b = &d; is allowed in above program. Output Content of base class. In above program, even if the object of derived class d is put in pointer to base class, display( )of the base class is executed( member function of the class that matches the type of pointer ). Virtual Functions If you want to execute the member function of derived class then, you can declare display( ) in the base class virtual which makes that function existing in appearance only but, you can't call that function. In order to make a function virtual, you have to add keyword virtual in front of a function.

86 #include <iostream>
#include<conio.h> class B { public: virtual void display() /* Virtual function */ { cout<<"Content of base class.\n"; } };  class D1 : public B void display() { cout<<"Content of first derived class.\n"; }  class D2 : public B { cout<<"Content of second derived class.\n"; } void main() B *b;

87 basic Input Output D1 d1; D2 d2; b = &d1; b->display(); b = &d2;
b->display(); /* calls display() of class derived D2 */ return 0; } basic Input Output C++ uses a convenient abstraction called streams to perform input and output operations in sequential media such as the screen, the keyboard or a file. A stream is an entity where a program can either insert or extract characters to/from.  The standard library defines a handful of stream objects that can be used to access what are considered the standard sources and destinations of characters by the environment where the program runs:

88 #include <iostream>
 int main () { int i; cout << "Please enter an integer value: "; cin >> i; cout << "The value you entered is " << i; cout << " and its double is " << i*2 << ".\n"; return 0; } #include <string> using namespace std; string mystr; cout << "What's your name? "; getline (cin, mystr); cout << "Hello " << mystr << ".\n"; cout << "What is your favorite team? "; cout << "I like " << mystr << " too!\n";

89 #include <iostream>
#include <string> using namespace std; int main () { string mystr; float price=0; int quantity=0; cout << "Enter price: "; getline (cin,mystr); stringstream(mystr) >> price; cout << "Enter quantity: "; stringstream(mystr) >> quantity; cout << "Total price: " << price*quantity << endl; return 0; } I/O Manipulators The following output manipulators control the format of the output stream. Include <iomanip> if you use any manipulators that have parameters; the others are already included with <iostream>. The Range column tells how long the manipulator will take effect: now inserts something at that point, next affects only the next data element, and all affects all subsequent data elements for the output stream.

90 file handling: Templates:
C++ provides the following classes to perform output and input of characters to/from files:  ofstream: Stream class to write on files ifstream: Stream class to read from files fstream: Stream class to both read and write from/to files. Templates: Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. A template is a blueprint or formula for creating a generic class or a function. The library containers like iterates and algorithms are examples of generic programming and have been developed using template concept. we can use templates to define functions as well as classes, let us see how do they work: Function Template: The general form of a template function definition is shown here:

91 /*PROGRAME RELATED TO TEMPLATE */
#include<iostream.h> #include<conio.h> template<class T1, class T2> class MyClass { private: T1 i; T2 j,c; public: void Put(); void Get(); T2 Multi(); }; cont..

92 template<class T1, class T2>
void MyClass<T1,T2>::Put() { cout << "The Product is : " << c << endl; } void MyClass<T1,T2>::Get() cout << "Enter the value of x : "; cin >> i; cout << "Enter the value of y : "; cin >> j; T2 MyClass<T1,T2>::Multi() c = i*j; return c;

93 void main() { clrscr(); MyClass<int,int> a; MyClass<int,double> b; a.Get(); a.Multi(); a.Put(); b.Get(); b.Multi(); b.Put(); getch(); }

94 THANK YOU


Download ppt "C++ Programming."

Similar presentations


Ads by Google