You are on page 1of 69

Object-Oriented Programming

Object-Oriented Programming CONSTRUCTORS AND DESTRUCTORS C++ provides a special member function called the constructor which enables an object to initialize itself when it is created. It is special in the sense that its name is same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it construct the values of data members of the class. A constructor is declared and defined as follows class class_name { private data and functions public: public data and functions class_name (); //constructor declared

}; class_name :: class_name () //constructor defined { Initialization of private data; } A constructor that accepts no parameters is called the default constructor. Example L8x1.cpp

/* Example of constructor*/ void line(); class list { int x[3][3]; public: list(void); //constructor declaration

void display(void);Object-Oriented Programming

}; list::list(void) { for(int i=0;i<3;i++) for(int j=0;j<3;j++) x[i][j]=random(99); //random(int num) is defined in <stdlib.h> } void list::display(void) { for(int i=0;i<3;i++) { for(int j=0;j<3;j++) cout<<x[i][j]<<"\t"; cout<<"\n"; } //constructor definition

} void line() { cout<<"\n-----------------------------------\n"; } main() { list test1,test2; line(); cout<<"Object test1:\n"; test1.display(); line(); cout<<"Object test2:\n"; test2.display(); line(); getche(); } The constructor functions have some special characteristics: - should be declared in the public section - invoked automatically when objects are created - do not have return types, not even void and therefore, they can t return valuesObject-Oriented Programming

- a derived class can call the base class constructor - can t be inherited

Parameterized Constructors The constructor list(void), defined in the example above, initializes the data members of all the objects to a random number. In practice, it is necessary to initialize the various data elements of different objects with different values when they are created. C++ allows to achieve this by passing arguments to the constructor function when objects are created. These constructors are called parameterized constructors. The general form is shown below class class_name { private data and functions public: public data and functions class_name (parameter list); //constructor declared

}; class_name :: class_name (parameter list) //constructor defined { Initialization of private data; } Example point.hpp /* Example of class point.hpp*/ #include <stdio.h> #include <iostream.h> #include <conio.h>

#include <math.h> class point { int x; int y; public:Object-Oriented Programming

point(int a, int b); { x=a; y=b; }

//constructor with parameter declared // defined

void display(void); }; Example L8x3.cpp /* Example of parameterized constructor*/ #include "point.h" #include <stdlib.h> void line(); /* The class is defined in header file point.h class point { int x; int y; public:

point(int, int); void display(void); }; */

//constructor declaration

point::point(int a, int b) //constructor definition { x=random(a); y=random(b); } void point::display(void) { cout<<"(x,y)=("<<x<<","<<y<<")\n"; } void line() { cout<<"\n-----------------------------------\n"; }Object-Oriented Programming

main() { point p1(15,30),p2(54,29); line(); cout<<"Object p1"; p1.display(); line(); cout<<"Object p2";

p2.display(); line(); getche(); } Copy Constructors The sets of values of one object can be copied into the corresponding elements of another object. Such a constructor is called copy constructor. The example below shows a copy constructor. Example L8x4.cpp /* Example of parameterized constructor*/ #include <stdio.h> #include <iostream.h> #include <conio.h> #include <math.h> #include <stdlib.h> class point { int x; int y; public: point(int a, int b) //constructor declaration { x=random(a); y=random(b); } //constructor definition

point (point & p); //copy constructor /* {Object-Oriented Programming

x=p.x; y=p.y; } */ void display(void); }; point::point(point & p) //constructor definition { x=p.x; y=p.y; } void point::display(void) { cout<<"(x,y)=("<<x<<","<<y<<")\n"; } main() { point p1(15,30); point p2(p1); //copying object p1 into p2 point p3=p2; //copying object p2 into p3 cout<<"\n-----------------------------------\n"; cout<<"Object p1"; p1.display();

cout<<"\n-----------------------------------\n"; cout<<"Object p2"; p2.display(); cout<<"\n-----------------------------------\n"; cout<<"Object p3"; p3.display(); cout<<"\n-----------------------------------\n"; getche(); }Object-Oriented Programming

Dynamic Initialization of Objects To initialize value of an object during run-time is called dynamic initialization. This is done using over loaded constructors. This provides the flexibility of using different format of data at run time. This is done by an empty constructor, e.g. point() { } and then defining the constructor with parameters, e.g. point(int a, int b) {x=a; y=b; } And then call the constructor with actual parameters, e.g. int p1=point(x1,y1); Example L8x5.cpp /* Example of dynamic initialization of constructor*/ #include <stdio.h> #include <iostream.h> #include <conio.h> #include <math.h> #include <stdlib.h>

class point { int x; int y; public: point() {} point(int a, int b) //constructor declaration { x=a; y=b; } //constructor definition

void display(void); }; void point::display(void) { cout<<"(x,y)=("<<x<<","<<y<<")\n"; } main() {Object-Oriented Programming

// point p1,p2; //can be done here int x1,y1; cout<<"Enter x value: "; cin>>x1;

cout<<"Enter y value: "; cin>>y1; point p1=point(x1,y1); //dynamic initialization point p2=p1; //copying object p1 into p2

cout<<"\n-----------------------------------\n"; cout<<"Object p1"; p1.display(); cout<<"\n-----------------------------------\n"; cout<<"Object p2"; p2.display(); cout<<"\n-----------------------------------\n"; getche(); } Dynamic memory allocation When a variable is declared, compiler allocates a block of memory large enough to store a value of the specified type. This allocation cannot be changed during run-time unless the program is rewritten. C++ provides operations such as new and delete to perform memory allocation and deallocation during execution. The general form of such operations is as follows type *Ptr; .. .. Ptr = new type[size]; .. ..

delete Ptr; Example L8x6.cpp /* Example of new and delete */ #include <stdio.h> #include <iostream.h> #include <conio.h> #include <math.h>Object-Oriented Programming

#include <stdlib.h> #define NULL 0 main() { int *p,*tb1; int size; cout<<"\n What is the size of table ? "; cin>>size; printf("\n"); /* memory allocation */ tb1=new int[size]; if(tb1==NULL) { cerr<<"No space available \n"; exit(-1); } printf("\n Address of the first byte is: %u\n",tb1);

/* Reading table values */ cout<<"\n Input table values \n"; for(p=tb1;p<tb1+size;p++) cin>>*p; cout<<"\nPrinted in reverse order \n\n"; for(p=tb1+size-1;p>=tb1;p--) printf("%d is stored at address %u\n",*p,p); delete tb1; cout<<"\n tb1 deleted\n\n"; getch(); }Object-Oriented Programming

Dynamic constructors Constructors can also be used to allocate memory while creating objects. This will enable the system to allocate the right amount of memory for each object when objects are not of the same size. Memory is allocated with the use of new operator. Example L8x7.cpp /* Example of dynamic constructor */ #include <stdio.h> #include <iostream.h> #include <conio.h> #include <math.h> class list {

int *p; //pointer to a list int size; //dimension public: list(int x); //constructor declaration void get(int i, int val) {p[i]=val;} int display(int i) {return p[i];} }; list :: list(int x) { size=x; p=new int[size]; //creates space for a new element } main() { int n; cout << "Enter size of list: \n"; cin >> n; list A(n); cout << "Enter elements in a row\n"; int j,val; for(j=0;j<n;j++) {Object-Oriented Programming //constructor definition

cin >> val; A.get(j,val); } cout<<"\n"; cout<<"list elements are \n"; cout<<"-----------------------------------\n"; for(j=0;j<n;j++) cout << A.display(j)<< "\t"; cout << "\n"; getche(); } Using the concept of dynamic constructor, two-dimensional array variables can be constructed. This is shown in example below.

Example L8x8cpp class table { int **tbl; //pointer to table int dim1, dim2; //dimension public: table(int x, int y); //constructor declaration void get(int i, int j, int value) {tbl[i][j]=value;} int display(int i, int j) {return tbl[i][j];}

}; table :: table(int x, int y) { dim1=x; dim2=y; tbl=new int *[dim1]; //creates an array of pointer for (int i=0; i<dim1;i++) tbl[i]=new int[dim2]; //space for new element of array } main() { int m,n; cout << "Enter size of table: \n";Object-Oriented Programming //constructor definition

cin >> m >> n; table A(m,n); cout << "Enter matrix element row by row \n"; int i,j,val; for(i=0;i<m;i++) for(j=0;j<n;j++) { cin >> val; A.get(i,j,val); } cout<<"\n";

cout<<"Matrix elements are \n"; cout<<"-----------------------------------\n"; for(i=0;i<m;i++) { for(j=0;j<n;j++) cout << A.display(i,j)<< " "; cout << "\n"; } cout<<"-----------------------------------\n"; getche(); } Destructors A destructor is used to destroy the objects that have been created by a constructor. Like a constructor, destructor is a member function whose name is the same as the class name but is preceded by ~ (tilde). A destructor never takes any argument. It will be invoked implicitly by the compiler upon exit from the program to clean up memory space for future use. This is shown in the example below. Example class point { int x; int y; public: point(int a, int b); //constructor with parameter declared

// defined

x=a;Object-Oriented Programming

y=b; } ~point(); //destructor declared

void display(void); };

. . point :: ~point() //destructor defined { delete x; delete y; } Example class table { int **tbl; //pointer to table int dim1, dim2; //dimension public: table(int x, int y); //constructor declared ~table(); //destructor declared void get(int i, int j, int value)

{tbl[i][j]=value;} int display(int i, int j) {return tbl[i][j];} }; table :: table(int x, int y) { dim1=x; dim2=y; tbl=new int *[dim1]; for (int i=0; i<dim1;i++) tbl[i]=new int[dim2]; } table :: ~table() { for (int i=0; i<dim1;i++) delete tbl[i]; delete tbl; }Object-Oriented Programming //destructor definition //constructor definition

Example L8x9.cpp /* Example of destructor */ #include <stdio.h> #include <iostream.h> #include <conio.h> #include <math.h>

class table { int **tbl; //pointer to table int dim1, dim2; //dimension public: table(int x, int y); //constructor declared ~table(); //destructor declared void get(int i, int j, int value) {tbl[i][j]=value;} int display(int i, int j) {return tbl[i][j];} }; table :: table(int x, int y) { dim1=x; dim2=y; tbl=new int *[dim1]; for (int i=0; i<dim1;i++) tbl[i]=new int[dim2]; } table :: ~table() { for (int i=0; i<dim1;i++) delete tbl[i]; delete tbl; //destructor definition //constructor definition

} main() { int m,n; cout << "Enter size of table: \n"; cin >> m >> n;Object-Oriented Programming

table A(m,n); cout << "Enter matrix element row by row \n"; int i,j,val; for(i=0;i<m;i++) for(j=0;j<n;j++) { cin >> val; A.get(i,j,val); } cout<<"\n"; cout<<"Matrix elements are \n"; cout<<"-----------------------------------\n"; for(i=0;i<m;i++) { for(j=0;j<n;j++) cout << A.display(i,j)<< " "; cout << "\n"; }

cout<<"-----------------------------------\n"; getch(); } CLASSES Object-Oriented Programming

Classes Objected Oriented Modelling is a new way of visualising problems using models organised around the real world concepts. Objects are the result of programming methodology rather than a language. Class grouping data and functions Object Oriented Programming constructs modelled out of data types called classes. A Class encloses both the data and functions that operate on the data, into a simple unit. The variable and functions enclosed in a class are called data members and member functions respectively. Class Specifications The syntax of a class specification is Syntax : class ClassName { Private : data member-list Public : member functions } [declarators];

[ class ] tag declarators; The class specifies the type and scope of its members. The keyword class indicates that the name which follows (ClassName) is an abstract datatype. The body of a class is enclosed within the curly braces followed by a ; (semi coloumn) the end of a class specification. The variables declared inside a

class are known as data members, and functions are known as member Data1 Data2 Data3 Data Functions Func1() Func2() Func3() Functions Body of the ClassObject-Oriented Programming

functions. These members are usually grouped under two sections private and public, which define the visibility of members. The private members are accessible only two their own class s members. On the other hand, public members are not only accessible to their own members, but also from outside the class. The members in the beginning of the class without any access specifier are private by default. Example : Class Account

{ private: char name[20]; //data members int accounttype; int accountnumber; float balance public: deposit(); //member functions withdraw(); enquire(); }; Class Objects A class specification only declares the structure of objects and it must be instantiated in order to make use of the services provided by it. This process of creating objects (Variables) of the class is called class instantiation. The syntax for defining objects of a class is class ClassName ObjectName; The keyword class is optional. For e.g.: account savings_account; account current_account; account FD_account; Create instances of the class account. The following points on classes can be noted: A class is a template that unites data and operations. A class is an abstraction of the real world entities with similar properties.

A class identifies a set of similar objects. Ideally, the class is an implementation of abstract data type.Object-Oriented Programming

Accessing Class members Once an object of a class has been created, there must be a provision to access its members. This is achieved by using the member access operator (.) Dot. The syntax for accessing members (Data and Functions) of a class is a) Accessing data member ObjectName . DataMember b) Accessing member functions ObjectName . MemberFunction(Actual Arguments); Defining Member Functions The data members of a class must be declared within the body of the class, where as the member functions of a class can be defined in any one of the following base a) Inside the class specification b) Outside the class specification Member Functions Inside the class body The syntax for specifying a member function declaration is similar to a normal function definition except that it is enclosed within the body of a class. Example class Date { private : int day;

int moth; int year; public : void set(int dayin, int monthin, int yearin) // declaration inside the class { day=dayin;

month = monthin; year = yearin; } }; Member Functions Outside the class body Another method of defining a member function is to declare function prototypes within the body of a class and then define it outside the body of the class. Since the function define outside class is done by using the scope resolution operator (::). The general format of a function definition is Object-Oriented Programming

class ClassName { RetrunType MemberFunction(Arguments); }; // end of class ReturnType ClassName :: MemberFunction(Arguments) { // Body of the function } DATA ABSTRACTION AND ENCAPSULATION

A data type, such as the native data types int, float, ...is characterised by: A set of values - that can be assumed by objects of the type. A set of operations that can be performed on objects of the type. Data Abstraction allows for information hiding creation of abstract data types that are not built into the programming language Every data type in a programming language consists of: a set of values a collection of operations Example class absdata { int a; float b; public: void get(int x, float y) { a=x; b=y; } void negative() { a=-a; b=-b; cout<<"\n-tive Output:"<<a; cout<<"\n-tive Output:"<<b;Object-Oriented Programming

} };

A variable of type int can only hold values ranging in the set of integers, and can participate in operations, such as addition, subtraction, multiplication, etc. Abstract data types also consist of a set of values and a collection of operations consistent with the values of the data type. They are implemented in a manner that any value of the type can be created and used through the allowable set of operations. The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those functions which are wrapped in the class can access it. This insulation of the data from direct access by the program is called data hiding. To implement an ADT, we must first choose a data representation for its values using existing data types, and then implement the allowable operations for the type. Classes use the concept of abstraction and are defined as list of abstract attributes. Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT). Example class funny { char fat[10]; int float cat; public: void HipHip(void) { big;

. .. } void TipTip(void) { . . } }Object-Oriented Programming

Example class Person { char name[15]; int height; int age; public: CanRun() { 'Code that makes the person run } CanCry() { 'Code that make the person cry }

CanRead() { 'Code that determines if the person can read } } Example L8x10.cpp class absdata { int a; float b; public: void get(int x, float y) { a=x; b=y; } void negative() { a=-a; b=-b; cout<<"\n-tive Output:"<<a; cout<<"\n-tive Output:"<<b; } void doubleup()Object-Oriented Programming

{ a=a+a; b=b+b;

cout<<"\n double -tive:"<<a; cout<<"\n double -tive:"<<b; } }; main() { absdata A; A.get(5,6.0); cout<<"Object test1:\n"; A.doubleup(); A.negative(); getch(); } Data Hiding The data is hidden inside a class, so that it can t be access even by mistake by any functions outside class, which is a key feature OOP. C++ imposes a restriction to access both the data and functions of a class. All the data and functions defined in a class are private by default. Normally, data members are declared as private and members functions are declared as public. The mechanisms to access even private data using friends, pointer to members etc.. from outside the class. Private members The private members of a class have strict access control. Only the member functions of the same class can access these members. The private members of a class are in accessible outside the class, thus providing a mechanism for

preventing accidental modifications of data members. class person { private: //private members int age; int getage(); };Object-Oriented Programming

person p1; a=p1.age; // Can not access private data p1.getage(); // Can not access private function Protected Members The access control of the protected members is similar to that of private members and as most significance in inheritance. class person { protected: // protected members int age; int getage(); }; person p1; a=p1.age; // Cannot access protected data member p1.getage(); // Cannot access protected member function

Public Members The members of a class which are to be visible (accessible) outside the class, should be declared in public section. All data members and functions declared in the public section of the class can be accessed without any restriction from any where in the programe. class person { public: // public members int age; int getage(); }; person p1; a=p1.age; // Can access public data member p1.getage(); // Can access public member functionObject-Oriented Programming

Visibility of class members Access Specifier Accessible to Own class members Objects of a class Private Yes No Protected Yes No Public Yes Yes Friend Functions and Friend Classes One of the convenient and controversial feature of C++ is allowing nonmember functions to access even the private members of a class using friend functions or friend classes. It permits a function or all the functions of another

class to access a different class s private members. The function declaration must be prefixed by the keyword friend where as the function definition must not. The function could be defined any where in the programe similar to any normal c++ function. The function that are declared with keyword friend are called friend functions. A function can be a friend to multiple classes. A friend function posses the following special characteristics. The scope of a friend function is not limited to the class in which it has been declared as friend. The friend function can t be called using the object of their class. It is not in the scope of the class. It can be invoked like a normal function without the use any object. Unlike class member functions, it can t access the class members directly, however, it can use the object and the dot(.) operator with each member name to access both the private and public members. It can be either declared in the private path or the public path of a class without affecting its meaning. Example: #include <iostream.h> #include <conio.h> class two; // advance declaration like function prototype; class one { private: int data1; public:Object-Oriented Programming

void setdata(int init) { data1 = init; } friend int add_both(one a, two b); // friend function }; class two { private: int data2; public: void setdata( int init) { data2 = init; } friend int add_both(one a, two b); // friend function }; // friend function of class one and two int add_both(one a, two b) { return (a.data1+ b.data2); // a.data1 and b.data2 are private } void main() { one a;

two b; clrscr(); a.setdata(5); b.setdata(10); cout<< \nSum of one and two : <<add_both(a, b); getch(); } FUNCTIONS Object Oriented Programming (Lecture notes on Functions) Hello welcome to everyone here I will discuss functions in C++ and what the basic difference of functions is in C language and C++ language. In C language as we have seen functions are powerful way of modularizing the program, and it helped in reusability of the code. In C++ we have two basic differences in function declaration and usages Unlike C, function return type is not optional and it is not going to take any default return type. So if you are not going to return any value write void as return type. EX:Here in C++ we have added some additional features to functions from what we had in C, they are 1. Function overloading 2. Passing default values to the parameters 3. Inline Functions 4. Call by reference variable

#include<iostream> #include<windows.h> using namespace std; int fun (int a ,float b ) { cout<< Enter the Value of a and b <<endl; cin>>a>>b; return (a); } int main() { Int z; // function returning value of a // function with return type of int

z= fun(10,20);

//calling function with 10 and 20 as parameter

fun(30,40); // calling function with parameters 30,40 but not storing return value anywhere system( pause ); return (0); } Function Overloading: So as by name suggests it is use of same thing for different purposes. C++ permits overloading of functions. That means we can use the same function name to create functions that perform a variety of different tasks. This is known as function overloading or function polymorphism. Using this we can write family of functions with one function name but with different arguments list. Every function must be distinctive from other. According to the arguments passed corresponding function would be called.

EX:- addition of two numbers Passing default values to arguments C++ allows us to call a function without specifying all its arguments. In such cases the function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when function is declared. EX:int amount(float principal , int period, float rate=0.15 );

The default values are specified in a manner syntactically similar to a variable initialization. Above prototype declares a default value of 0.15 to the argument rate. A subsequent function call like Value = amount (5000.2, 7); //one argument missing rate is given =0.15(default) So now it supplies default value 0.15 to rate. When you call function all three arguments then it will supply the values from it to arguments Value= amount (500.3, 20, 0.75); // so now rate will be given = 0.75

One important point to note is that only the trailing arguments can have default values and therefore we must add defaults from right to left. we cannot provide a default values to a particular argument in the middle of an argument list. #include<iostream> #include<windows.h> using namespace std; // declaration of different functions int add(int a, int b); // prototype 1 //prototype 2 //prototype 3

double add(int a, int b, double c) ; double add(double a, double b);

// Functions calls add (10,20); //function of prototype 1 called

add (20.3, 30.4); //function of prototype 3 called add (10 , 10, 20.1) // function of prototype 2 calledSome examples are here: int mul (int i, int j=5, int k= 10 ); int mul(int i=5, int j); int mul (int i=0, int j, int k=10); int mul (int i=2, int j=5, int k=10); Inline Functions: This inline functions is somewhat similar to macros (pre-processor directives such as # define PI=3.14 ) which indicates compiler that where it sees PI in source code replace it by 3.14. Similarly inline specifier indicates the compiler that inline substitution is preferred to the usual function call mechanism for a specific function. This does not change the behaviour of a function itself, but is used to suggest to the compiler that the code generated by the function body is inserted at each point the function is called, instead of being inserted only once and perform a regular call to it, which generally involves some additional overhead in running time. for example inline int square(int x) { return (x * x); } int main() { . square(5); } // legal //illegal //illegal // legal

Just like define macro function body function body is inserted at function call. There are few advantages and disadvantages of using inline functions Advantages: when function body is small and it is regularly called, in such situations inline function reduces the overhead of calling the function, which requires making of stack, emptying registers. This time will be saved as you very few numbers of lines of code, which will be inserted by compiler. Disadvantage: But in-case when you have large number of lines of code in function body and tries to use Inline functions then compiler will be taking large amount of time to compile as it has to insert large code. So this will become more overhead than making stacks and emptying registers. Function Overloading Function polymorphism, or function overloading is a concept that allows multiple functions to share the same name with different argument types. Assigning one or more function body to the same name is known as function overloading or function name overloading. A function is overloaded when same name is given to different function. However, the two functions with the same name will differ at least in one of the following. a) The number of parameters b) The data type of parameters c) The order of appearance These three together are referred to as the function signature. For example if we have two functions : void foo(int i,char a); void boo(int j,char b); Their signature is the same (int ,char) but a function void moo(int i,int j) ; has a signature (int, int) which is different.

While overloading a function, the return type of the functions need to be the same. In general functions are overloaded when : 1. Functions differ in function signature. 2. Return type of the functions is the same. Here is a basic example of function overloading #include <iostream> using namespace std; class arith { public: void calc(int num1) { cout<<"Square of a given number: " <<num1*num1 <<endl; } void calc(int num1, int num2 ) { cout<<"Product of two whole numbers: " <<num1*num2 <<endl; } };int main() //begin of main function { arith a; a.calc(5); a.calc(6,7); } First the overloaded function in this example is calc. If you have noticed we have in ourarith class two functions with the name calc. The fist one takes one integer number as a

parameter and prints the square of the number. The second calc function takes two integer numbers as parameters, multiplies the numbers and prints the product. This is all we need for making a successful overloading of a function. a) we have two functions with the same name : calc b) we have different signatures : (int) , (int, int) c) return type is the same : void The result of the execution looks like this Square of a given number: 25 Product of two whole numbers: 42 The result demonstrates the overloading concept. Based on the arguments we use when we call the calc function in our code : a.calc(5); a.calc(6,7); The compiler decides witch function to use at the moment we call the function depending on the context. If there is any ambiguity your compiler will give an error. What is Inline Function? Inline functions are functions where the call is made to inline functions. The actual code then gets placed in the calling program. Reason for the need of Inline Function: Normally, a function call transfers the control from the calling program to the function and after the execution of the program returns the control back to the calling program after the function call. These concepts of function saved program space and memory space are used because the function is stored only in one place and is only executed when it is called. This concept of function execution may be time consuming since the registers and other processes must be saved before the function gets called.

The extra time needed and the process of saving is valid for larger functions. If the function is short, the programmer may wish to place the code of the function in the calling program in order for it to be executed. This type of function is best handled by the inline function. In this situation, the programmer may be wondering why not write the short code repeatedly inside the program wherever needed instead of going for inline function? Although this could accomplish the task, the problem lies in the loss of clarity of the program. If the programmer repeats the same code many times, there will be a loss of clarity in the program. The alternative approach is to allow inline functions to achieve the same purpose, with the concept of functions. What happens when an inline function is written? The inline function takes the format as a normal function but when it is compiled it is compiled as inline code. The function is placed separately as inline function, thus adding readability to the source program. When the program is compiled, the code present in function body is replaced in the place of function call. General Format of inline Function: The general format of inline function is as follows: inline datatype function_name(arguments) The keyword inline specified in the above example, designates the function as inline function. For example, if a programmer wishes to have a function named exforsys with return value as integer and with no arguments as inline it is written as follows: inline int exforsys( )Example: The concept of inline functions: #include <iostream.h> int exforsys(int); void main( )

{ int x; cout << \n Enter the Input Value: ; cin>>x; cout<< \n The Output is: << exforsys(x); } inline int exforsys(int x1) { return 5*x1; } The output of the above program is: Enter the Input Value: 10 The Output is: 50 The output would be the same even when the inline function is written solely as a function. The concept, however, is different. When the program is compiled, the code present in the inline function exforsys( ) is replaced in the place of function call in the calling program. The concept of inline function is used in this example because the function is a small line of code. The above example, when compiled, would have the structure as follows: #include <iostream.h> int exforsys(int); void main( ) { int x; cout << \n Enter the Input Value: ;

cin>>x; //The exforsys(x) gets replaced with code return 5*x1; cout<< \n The Output is: << exforsys(x); }When the above program is written as normal function the compiled code would look like below: #include <iostream.h> int exforsys(int); void main( ) { int x; cout << \n Enter the Input Value: ; cin>>x; //Call is made to the function exforsys cout<< \n The Output is: << exforsys(x); } int exforsys(int x1) { return 5*x1; } A programmer must make wise choices when to use inline functions. Inline functions will save time and are useful if the function is very small. If the function is large, use of inline functions must be avoided. CLASSES Object-Oriented Programming

Classes Objected Oriented Modelling is a new way of visualising problems using models organised around the real world concepts. Objects are the result of programming methodology rather than a language. Class grouping data and functions Object Oriented Programming constructs modelled out of data types called classes. A Class encloses both the data and functions that operate on the data, into a simple unit. The variable and functions enclosed in a class are called data members and member functions respectively. Class Specifications The syntax of a class specification is Syntax : class ClassName { Private : data member-list Public : member functions } [declarators]; [ class ] tag declarators; The class specifies the type and scope of its members. The keyword class indicates that the name which follows (ClassName) is an abstract datatype. The body of a class is enclosed within the curly braces followed by a ; (semi coloumn) the end of a class specification. The variables declared inside a

class are known as data members, and functions are known as member

Data1 Data2 Data3 Data Functions Func1() Func2() Func3() Functions Body of the ClassObject-Oriented Programming

functions. These members are usually grouped under two sections private and public, which define the visibility of members. The private members are accessible only two their own class s members. On the other hand, public members are not only accessible to their own members, but also from outside the class. The members in the beginning of the class without any access specifier are private by default. Example : Class Account { private: char name[20]; //data members int accounttype; int accountnumber; float balance

public: deposit(); //member functions withdraw(); enquire(); }; Class Objects A class specification only declares the structure of objects and it must be instantiated in order to make use of the services provided by it. This process of creating objects (Variables) of the class is called class instantiation. The syntax for defining objects of a class is class ClassName ObjectName; The keyword class is optional. For e.g.: account savings_account; account current_account; account FD_account; Create instances of the class account. The following points on classes can be noted: A class is a template that unites data and operations. A class is an abstraction of the real world entities with similar properties. A class identifies a set of similar objects. Ideally, the class is an implementation of abstract data type.Object-Oriented Programming

Accessing Class members Once an object of a class has been created, there must be a provision to access its members. This is achieved by using the member access operator (.)

Dot. The syntax for accessing members (Data and Functions) of a class is a) Accessing data member ObjectName . DataMember b) Accessing member functions ObjectName . MemberFunction(Actual Arguments); Defining Member Functions The data members of a class must be declared within the body of the class, where as the member functions of a class can be defined in any one of the following base a) Inside the class specification b) Outside the class specification Member Functions Inside the class body The syntax for specifying a member function declaration is similar to a normal function definition except that it is enclosed within the body of a class. Example class Date { private : int day; int moth; int year; public : void set(int dayin, int monthin, int yearin) // declaration inside the class { day=dayin;

month = monthin; year = yearin; } }; Member Functions Outside the class body Another method of defining a member function is to declare function prototypes within the body of a class and then define it outside the body of the class. Since the function define outside class is done by using the scope resolution operator (::). The general format of a function definition is Object-Oriented Programming

class ClassName { RetrunType MemberFunction(Arguments); }; // end of class ReturnType ClassName :: MemberFunction(Arguments) { // Body of the function } DATA ABSTRACTION AND ENCAPSULATION A data type, such as the native data types int, float, ...is characterised by: A set of values - that can be assumed by objects of the type. A set of operations that can be performed on objects of the type. Data Abstraction allows for information hiding creation of abstract data types that are not built into the programming

language Every data type in a programming language consists of: a set of values a collection of operations Example class absdata { int a; float b; public: void get(int x, float y) { a=x; b=y; } void negative() { a=-a; b=-b; cout<<"\n-tive Output:"<<a; cout<<"\n-tive Output:"<<b;Object-Oriented Programming

} }; A variable of type int can only hold values ranging in the set of integers, and can participate in operations, such as addition, subtraction, multiplication, etc. Abstract data types also consist of a set of values and a collection of operations consistent with the values of the data type. They are implemented in a manner that any value of the type can be created and used through the allowable set of operations.

The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those functions which are wrapped in the class can access it. This insulation of the data from direct access by the program is called data hiding. To implement an ADT, we must first choose a data representation for its values using existing data types, and then implement the allowable operations for the type. Classes use the concept of abstraction and are defined as list of abstract attributes. Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT). Example class funny { char fat[10]; int float cat; public: void HipHip(void) { . .. } void TipTip(void) { . big;

. } }Object-Oriented Programming

Example class Person { char name[15]; int height; int age; public: CanRun() { 'Code that makes the person run } CanCry() { 'Code that make the person cry } CanRead() { 'Code that determines if the person can read } } Example L8x10.cpp

class absdata { int a; float b; public: void get(int x, float y) { a=x; b=y; } void negative() { a=-a; b=-b; cout<<"\n-tive Output:"<<a; cout<<"\n-tive Output:"<<b; } void doubleup()Object-Oriented Programming

{ a=a+a; b=b+b; cout<<"\n double -tive:"<<a; cout<<"\n double -tive:"<<b; } }; main() {

absdata A; A.get(5,6.0); cout<<"Object test1:\n"; A.doubleup(); A.negative(); getch(); } Data Hiding The data is hidden inside a class, so that it can t be access even by mistake by any functions outside class, which is a key feature OOP. C++ imposes a restriction to access both the data and functions of a class. All the data and functions defined in a class are private by default. Normally, data members are declared as private and members functions are declared as public. The mechanisms to access even private data using friends, pointer to members etc.. from outside the class. Private members The private members of a class have strict access control. Only the member functions of the same class can access these members. The private members of a class are in accessible outside the class, thus providing a mechanism for preventing accidental modifications of data members. class person { private: //private members int age;

int getage(); };Object-Oriented Programming

person p1; a=p1.age; // Can not access private data p1.getage(); // Can not access private function Protected Members The access control of the protected members is similar to that of private members and as most significance in inheritance. class person { protected: // protected members int age; int getage(); }; person p1; a=p1.age; // Cannot access protected data member p1.getage(); // Cannot access protected member function Public Members The members of a class which are to be visible (accessible) outside the class, should be declared in public section. All data members and functions declared in the public section of the class can be accessed without any restriction from any where in the programe. class person

{ public: // public members int age; int getage(); }; person p1; a=p1.age; // Can access public data member p1.getage(); // Can access public member functionObject-Oriented Programming

Visibility of class members Access Specifier Accessible to Own class members Objects of a class Private Yes No Protected Yes No Public Yes Yes Friend Functions and Friend Classes One of the convenient and controversial feature of C++ is allowing nonmember functions to access even the private members of a class using friend functions or friend classes. It permits a function or all the functions of another class to access a different class s private members. The function declaration must be prefixed by the keyword friend where as the function definition must not. The function could be defined any where in the programe similar to any normal c++ function. The function that are declared with keyword friend are called friend functions. A function can be a friend to multiple classes. A friend function posses the following special characteristics.

The scope of a friend function is not limited to the class in which it has been declared as friend. The friend function can t be called using the object of their class. It is not in the scope of the class. It can be invoked like a normal function without the use any object. Unlike class member functions, it can t access the class members directly, however, it can use the object and the dot(.) operator with each member name to access both the private and public members. It can be either declared in the private path or the public path of a class without affecting its meaning. Example: #include <iostream.h> #include <conio.h> class two; // advance declaration like function prototype; class one { private: int data1; public:Object-Oriented Programming

void setdata(int init) { data1 = init; } friend int add_both(one a, two b); // friend function

}; class two { private: int data2; public: void setdata( int init) { data2 = init; } friend int add_both(one a, two b); // friend function }; // friend function of class one and two int add_both(one a, two b) { return (a.data1+ b.data2); // a.data1 and b.data2 are private } void main() { one a; two b; clrscr(); a.setdata(5); b.setdata(10); cout<< \nSum of one and two : <<add_both(a, b); getch();

} FRIEND FUNCTION ///*********************************************************************************** ********/// /// File : Demonstartion of classes and objects /// Purpose : Understanding of friend function /// Author : K . Amjath khan /// Mail Id : kotla.amjath@gmail.com /// Website : http://sites.google.com/site/oopskiit /// /// /// /// /// ///

/// This Code is tested with Bloodshed devc++ compiler version 4.9.9.2 on windows 7

///*********************************************************************************** *///

#include<iostream> #include<windows.h> using namespace std;

class friend_test {

private: int a,b;

public: void test() {

a=100; b=200; } friend int compute(friend_test e1); //Friend Function Declaration with keyword friend and with the object of class ABC to which it is friend passed to it };

int compute( friend_test e1) { //Friend Function Definition which has access to private data return (e1.a+e1.b)-5; }

int main() { friend_test e; e.test(); cout << "The result is:" << compute(e); //Calling of Friend Function with object as argument. system("pause"); return 0 } DESTRUCTORS

///*********************************************************************************** ********/// /// File : Demonstartion of classes and objects /// Purpose : Demonstration of destructors /// Author : K . Amjath khan /// Mail Id : kotla.amjath@gmail.com /// Website : http://sites.google.com/site/oopskiit /// /// /// /// /// ///

/// This Code is tested with Bloodshed devc++ compiler version 4.9.9.2 on windows 7

///*********************************************************************************** *///

#include<iostream> #include<windows.h> #include<string.h> // for using string functions such as strlen(), strcpy()

/* We have to understand what is need of destructor. Destructors are needed when we want to some operations at the time object is going out of scope . One of the important thing you want to do at the time of object out of scope is deleting the dynamic memory you have created for that object . Because the memory allocated for automatic variables will automatically dleted when object is going out of scope but dynamic memory don't. so we have to specifically delete it . As Destructor is automatically called when particularobject is going out of scope. In that we will delete the dynamic memory. */ using namespace std; class demo_dest

{ char *s,length; public: demo_dest() { length=0; } demo_dest(char *str) { cout<<"i am dynamic consructor\n"; length= strlen(str); s= new char[length+1]; // Allocating memory dynamically (new operator is used to allocate dynamic memory) strcpy(s,str); } /* Destructors (It will be called automatically when object is going out of scope) 1. Destructors have same name as Class name 2. before destructor you have ~ symbol 3. destructors won't have any return value 4.Destructors won't take any parameters 5.For one class you will be having only one destructor. unlike constructor you can't overload it */ ~demo_dest() { cout<<"i am destructor\n"; delete s; // Because object is going out of scope, we have //to release the memory which is allocated

// Dynamically. that is why we are deleting it. } };

int main() { char string1[40]; cout<<"\n Enter the string\n"; cin>>string1; demo_dest obj1("indian"); // so you are passing string demo_dest(char *) constructor will be called // which is now dynamic constructor demo_dest obj2(string1); // same as above

// starting a code of block //Dynamic constructor is called third time

demo_dest obj3(string1); // this object scope is limited to this block only because it is declared in this block

} // So now obj3 object is going out of scope so it will call destructor

system("pause"); return 0; } STATICS

///*********************************************************************************** ********/// /// File : Demonstartion of classes and objects /// Purpose : explaining Static variable of class /// Author : K . Amjath khan /// Mail Id : kotla.amjath@gmail.com /// Website : http://sites.google.com/site/oopskiit /// /// /// /// /// ///

/// This Code is tested with Bloodshed devc++ compiler version 4.9.9.2 on windows 7

///*********************************************************************************** *///

/* Static variable is common all objects of the class */

#include<iostream> #include<windows.h> using namespace std; class static_test { int a; static int p; public : void input() { cout<<"Enter the input values\n"; cin>>a; p++; // every time you call this function p value is incremented by 1 . And p is common to all objects

} void display() { cout<<"static p="<<p<<"\n"; cout<<"Its personnel variable a="<<a<<endl; } };

int static_test :: p; /* class is only abstract data type when you write class defination there is no memory is created for static members of the class . so After completion of class we have to define it. And default value of p is 0 */

int main() { static_test obj1,obj2,obj3; // obj1.p=10; will show error because it is private member of class and u can't access from outside obj1.input(); obj2.input(); obj3.input(); // Till now input function is called 3 times different objects but as p is static variable common to all objects obj1.display(); obj2.display(); obj3.display(); // Each time it will show p =3 as it is common to all objects

system("pause"); return 0; } CONSTRUCTER TESTING ///*********************************************************************************** ********/// /// File : Demonstartion of classes and objects /// Purpose : For more understanding of constructor /// Author : K . Amjath khan /// Mail Id : kotla.amjath@gmail.com /// Website : http://sites.google.com/site/oopskiit /// /// /// /// /// ///

/// This Code is tested with Bloodshed devc++ compiler version 4.9.9.2 on windows 7

///*********************************************************************************** *///

#include<iostream> #include<windows.h> using namespace std; class construct_test { int a,b,c; public : construct_test() { cout<<"i am in default constructor\n"; a=b=c=0;

} construct_test(int x,int y,int z) { cout<<"I am here in paramaterized constructor \n"; a=x; b=y; c=z; } construct_test(int x) { cout<<"Iam single parameter constructor\n"; a=b=c=x; } void display() { cout<<"x="<<a<<"y="<<b<<"z="<<c<<endl; } };

int main() { construct_test p= construct_test(2,3,4); // p object will be created by calling parameterized constructor construct_test q(10,20,30); // will be calling parameterized constructor p= construct_test(); // Default constructor will be called p.display();

// Even now you write for array of objects construct_test r[10]= construct_test(5); // 10 objets will be created by calling construct_test(int) constructor // with parameter 5

for(int i=0;i<10;i++) { r[i].display(); } system("pause"); return 0; }

You might also like