You are on page 1of 101

UNIT I PRINCIPLES OF OBJECT ORIENTED PROGRAMMING

INTRODUCTION The main pitfall with standard C has been identified as the lack of facilities for data abstraction. With the emergence of more abstract and modular languages like Modula-2 and Ada and Object-oriented languages like Small-Talk, BJARNE STROUSRUP at Bells Lab was motivated to develop C++ by upgrading C with appropriate mechanisms to create object like abstract data structures. The introduction of the class mechanism in C++ mainly provides the base for implementing abstract data types to suit object-oriented programming. The C++ language is thus considered as the superset of the standard C. IDENTIFIERS AND KEYWORDS Identifiers can be defined as the name of the variables and some other program elements using the combination of the following characters. Alphabets : az, AZ Numerals : 09 Underscore : _ Eg., NAME, A23C, CODE, EMP_NAME

Special characters : All characters other than listed as alphabets, numerals and underscore, are special characters.

Keywords Keywords are also identifiers but cannot be user defined since they are reserved words. Keywords in C++ Auto break case char const continue default do double else enum extern

float for goto if long register return short signed sizeof static struct switch union unsigned void volatile while Constants String constants Numeric constants Character constants

String constants A string constant is a sequence of alphanumeric characters enclosed in double quotation marks whose maximum length is 255 Characters. Eg. The man A343

Numeric Constants These are positive or negative numbers. Types of Numeric constants are :

Integer Integer Short Integer(short) Long Integer(long)

Float Single precision(float) Double precision(double) Long double

Unsigned Unsigned char Unsigned integer Unsigned short integer Unsigned long integer

Hex Short hexadecimal Long Hexadecimal

Octal Short octal Long octal

Operators Arithmetic operators (+, -, *, /, %) Assignment operators (=, +=, -=, *=, /=, %=) Comparison and Logical operators (<, >, <=, >=, ==,!=, &&, ||, !)

Relational operators (<, >, <=, >=) Equality operators (==, !=) Logical operators(&&, ||, !) Unary operators(*, &, -, !, ++, --, type, sizeof) Ternary operator (?) Scope operator(::) New and delete operators

Skeleton of typical C++ program Program heading Begin Type or variable declaration Statements of operation Results End Sample C++ program #include<iostream.h> void main() { cout << God is Great; } iostream The iostream supports both input/output stream of functions to read a stream of characters from the keyboard and to display a stream of objects onto the video screen. Input and Output statements Output Statement

The syntax cout << Message cout << variable_name cout << Message << variable_name

The << is called as insertion operator. Eg. Cout << god is great Cout << age Cout << name is << name

Input Statement The syntax.. Cin >> var1 >> var2 >> var3..varn; The >> is called as extraction operator. Eg. Cout << Enter a number Cin << a

Sample program to add, subtract, multiply and divide of the given two numbers #include<iostream.h> void main() { int a,b,sum,sub,mul,div; cout << Enter any two numbers << endln; cin >> a >> b;

sum=a+b; sub=a-b; mul=a*b; div=a/b; cout << Addition of two numbers is << sum; cout << Mulitiplication of two numbers is << mul; cout << Subtraction of two numbers is << sub; cout << Division of two numbers is << div; }

CONTROL STATEMENTS Conditional Statements The conditional expressions are mainly used for decision making. The following statements are used to perform the task of the conditional operations. if statement if-else statement switch-case statement

if Statement The if statement is used to express conditional expressions. If the given condition is true then it will execute the statements; otherwise it will execute the optional statements. If (expression) { Statement; Statement; ;; ;; }

if-else statement Syntax if (expression) statement; else statement; Syntax if (expression) { block-of-statements; } else { block-of-statements; } Nested if If (expression) { If (expression) { ********** ********** } else { ********* ********** } else { if (expression) { ******* **** }

else { ********* ********* } } A program to read any two numbers from the keyboard and to display the largest value of them. #include<iostream.h> void main() { float x,y; cout << Enter any two numbers \n; cin >> x >> y; if (x>y) cout << Biggest number is << x << endl; else cout << Biggest number is << y << endl; } switch statement The switch statement is a special multiway decision maker that tests whether an expression matches one of the number of constant values, and braces accordingly. Syntax switch (expression) { case contant_1 : Statements; case contant_2 : Statements; ;;

;; ;; case contant_n : Statements; default : Statement; }

A program to find out whether the given character is vowel or not #include<iostream.h> void main(){ char ch; cout << Enter the character : cin >> ch; switch(ch){ case A : case a : cout << The given character is vowel ; break; case E : case e : cout << The given character is vowel ; break; case I : case i : cout << The given character is vowel ; break; case O : case o : cout << The given character is vowel ; break; case U : case u :

cout << The given character is vowel ; break; default : cout << The given character is not vowel; break; }

Loop Statements A set of statements are to be executed continuously until certain condition is satisfied. There are various loop statements available in C++. for loop while loop do-while loop

for loop This loop consists of three expressions. The first expression is used to initialize the index value, the second to check whether or not the loop is to be continued again and the third to change the index value for further iteration. Syntax for (initial_condition; test_condition; increment or decrement value) { statement_1; statement_2; ;; ;; }

A Program to find the sum and average of given numbers #include<iostream.h> void main(){ int n; cout << Enter the no. of terms; cin >> n; float sum = 0; float a; for (int i=0; i<=n-1;++i) { cout << Enter a number :\n; cin >> a; sum = sum+a; } float av; av = sum/n; cout << sum= << sum << endl cout << Averave = << av << endl; } Nested For-Loops for(i=0;i<=n; ++i){ for(j=0; j<=m ; ++j) statements; statements; statements; }

while loop

This loop is used when we are not certain that the loop will be executed. After checking whether the initial condition is true or false and finding it to be true, only then the while loop will enter into the loop operations. Syntax While (Condition) Statement; For a block of statements, while(condition) { Statement_1; Statement_2; ------} Example while ((character = cin.get()) != EOF ) cout.put (character); do-while loop Whenever one is certain about a test condition, then the do-while loop can be used, as it enters into the loop at least once and then checks whether the given condition is true or false. Syntax do{ Statement_1; Statement_2; ----------} while (expression);

Example Sum=0; do { sum=sum+I; i++; } while (i<n); break statement The break statement is used to terminate the control from the loop statements of the caseswitch structure. This statement is normally used in the switch-case loop and in each case condition, the break statement must be used. If not, the control will be transferred to the subsequent case condition also. Syntax break; Continue statement This statement is used to repeat the same operations once again even if it checks the error. Syntax continue; go to statement This statement I used to alter the program execution sequence by transferring the control to some other part of the program. Syntax

goto label; There are two types of goto statements, which are conditional and unconditional goto statement. Unconditional goto This goto statement is used to transfer the control from one part of the program to other part without checking any condition. Example #include<iostream.h> void main(){ start: cout << God is Great; goto start; } Conditional goto This will transfer the control of the execution from one part of the program to the other in certain cases. Example If (a>b) goto big1;

big1:

Functions A function definition has a name, a parentheses pair containing zero or more parameters and a body. For each parameter, there should be a corresponding declaration that occurs before the body. Any parameter not declared is taken to be an int by default.

Syntax Function_type functionname(datatype arg1, datatype arg2,.) { body of function; ----------return value; }

return keyword This keyword is used to terminate function and return a value to its caller. This can be also used to exit a function without returning a value; Syntax return; return(expression); Types of Functions The user defined functions may be classified in the following three ways based on the formal arguments passed and the usage of the return statement, and based on that, there are three types of user-defined functions. a) A function is invoked without passing any formal argument from the calling portion of a program and also the function does not return back any value to the called function. b) A function is invoked with formal arguments from the calling portion of a program but the function does not return back any value to the calling portion. c) A function is invoked with formal arguments from the calling portion of a program which returns back a value to the calling environment. Type 1

Example #include<iostream.h> void main(){ void message() // function declaration message(); // function calling } void message(){ ------------------- // body of the function ---------} Type 2 Example #include<iostream.h> void main(){ void square(int ) // function declaration int a; ------------square(a); // function calling } void square(int x){ ------------------- // body of the function ---------} Type 3 Example #include<iostream.h> void main(){ int check(int,int,char) // function declaration int x,y,temp; char ch; ----------

---------temp=check(x,y,ch); // function calling } int check(int a, int b, char c){ int value; ------------------- // body of the function ---------return(value); } A program to find the square of its number using a function declaration without using the return statement #include<iostream.h> Void main() { void square(int); int max; cout << Enter a value for n ?\n; cin >> max; for (int i=0;i<=max-1;++i) square(i); } void square(int n) { float v; v=n*n; cout << I = << n << square = << value <<endl; } A program to find the factorial of a given number using function declaration with the return statement #include<iostream.h> void main(){ long int fact(int); int x,n; cout << Enter the no. to find factorial << endl; cin >> n; x=fact(n); cout << value = << n << and its factorial = ; cout << x << endl; } long int fact(int n)

{ int value=1; if (n == 1) return (value); else { for (int i=1;i<=n;++i) value = value * I; return(value); } } Local and Global variables Local variables Identifiers declared as label, const, type variables and functions in a block are said to belong to a particular block or function and these identifiers are known as the local parameters or variables. Local variables are defined inside a function block or a compound statement. Eg. Void funct(int I, int j) { int a,b; // local variables :: :; // body of the function } Global variables Global variables are variables defined outside the main function block. Eg. int a,b=10; // global variable declaration Void main() { void func1(); a=20; :: :; func1(); } func1() { int sum; sum=a+b; ::

:; } Storage Class Specifiers The storage class specifier refers to how widely it is known among a set of functions in a program. In other words, how the memory reference is carried out for a variable. Automatic variable Register Variable Static variable External variable

Automatic variable Internal or local variables are the variables which are declared inside a function. Eg. #include <iostream.h> void main() { auto int a,b,c; :: :: } Register Variable These variables are used for fast processing. Whenever some variables are to be read or repeatedly used, they can be assigned as register variables. Eg. function ( register int n) { register char temp; :: :: } Static Variable Static variables are defined within a function and they have the same scope rules of the automatic variables but in the case of static variables, the contents of the variables will be retained throughout the program. Eg. Static int x,y; External variable

Variables which are declared outside the main are called external variables and these variables will have the same data type throughout the program, both in main and in the functions. Eg. extern int x,y; extern float a,b; A program to display the no and its square from 0 to 10 using REGISTER variables. #include<iostream.h> void main() { int funt(registerint x, register int y); register int x,y,z; x=0; y=0; cout<<x y<<endl; do { z=funt(x,y); cout<<x<<\t<<z<<endl; ++x; ++y; } while(x<=10); } int funt(register int x, register int y); { register int temp; temp=x*y; return(temp); } Program to display 1 to 10 with addition of 100 using the automatic static variable. #include<iostream.h> void main() { int func(int x); int fun(int x1); int k,s,v; for (k=1;k<=10;k++) { v=func(k); s=fun(k); cout<<k<<\t<<v<<s<<endl; variable and the

} } func(int x) { int sum=100; // Automatic variable sum+=x; return(sum); } fun(int x1) { static int sum=100; // Static variable sum+=x1; return(sum); } Recursive Function A function which calls itself directly or indirectly again and again is known as the recursive function.

Program to find the factorial of the given no using the recursive function #include<iostream.h> void main() { long int fact(long int); int x,n; cin>>n; x=fact(n); cout<<n<<x<<endl; } long int fact(long int n); { long int fact(long int n); int v=1; if(n==1) return(v); else { v=n*fact(n-1); return(v); } } Arrays An array is a collection of identical data objects which are stored in consecutive memory locations under a common heading or a variable name.

Syntax Storage_class data_type array_name[expression]; Example int value[10]; char line[50]; static char page[20]; Array initialization int values[5] = {44,65,77,77,55}; char sex[] = { M, F}; float bpay[] = {423.0,43.5,656.4}; A program to initialize a set of numbers in the array and to display it in a standard output device #include <iostream.h> void main() { int a[5]={44,67,77,88,34,55}; int I; cout << Contents of the array \n; for (i=0;i<5;++i) { cout << a[i] << \t; } } Multidimensional Array These are defined in the same manner as one dimensional arrays, except that a separate pair of square brackets are required for each subscript. Syntax Storage_class data_type arrayname[expr1][expr2]..[exprn];

Example float coordinate x[4][4]; int value[10][5][5]; POINTERS A pointer is a variable which holds the memory address of another variable. Pointer operator A pointer operator can be represented by a combination of *(asterisk) with a variable. For eg. int *ptr; float *fp; The general format of pointer declaration is data_type *pointer_variable;

Address operator An address operator can be represented by a combination of & (ambersand) with a pointer variable. For eg. K = &ptr; Pointer Expressions Pointer assignment : A pointer is a variable data type and hence the general rule to assign its value to the pointer is same as that of any other variable data type.

Eg. int x,y; int *ptr1, *ptr2; ptr1 = &x; The memory address of variable x is assigned to the pointer variable ptr1. y = *ptr1; The contents of the pointer variable ptr1 is assigned to the variable y, not the memory address. ptr1 = &x; ptr2 = ptr1; The address of the ptr1 is assigned to the pointer variable ptr2. The contents of both prt1 and ptr2 will be the same as these two pointer variables hold the same address. A program to assign a character variable to the pointer and to display the contents of the pointer. #include <iostream.h> void main() { char x,y; char *pt; x = k; // assign character pt = &x; y = *pt; cout << Value of x = << x << endl; cout << Pointer value = << y << endl; } Structure

A structure is an aggregate of several data items that can be of different types, and it is defined using the keyword struct. The items are called members of the structure and are logically grouped. They convey information about the same object. Eg. struct student { int rollno; char name[20]; };

typedef The typedef is used to define new data items that are equivalent to the existing data types. Syntax typedef datatype newtype; Eg. typedef int integer; typedef float real; Integer a,b; real x,y; Features of C++ Class A group of objects that share common properties and relationship. In C++, a class is a new data type that contains member variables and member functions that operates on the variables. A class is defined with the keyword class.

Class Object A variable whose data type is a class. Structure of C++ Program A C++ program is similar to an ANSI C program except with some newly added types of declarations. Since CLASS types encapsulate all the functions, a C++ program may not have any subordinate function apart from the main function. A general structure of a program may look like < include standard header files> <include user-defined header files> <declaration of class type> <declaration of objects> void main() { declaration of local objects and variables statements } C++ class definition Syntax: <classkey> <classname> [<:baselist>] { <member list> } Classes are specific to C++. <classkey> is one of the keywords "class", "struct", or "union". <classname> can be any name unique within its scope. <baselist> lists the base class(es) that this class derives from. <baselist> is optional. <member list> declares the class's data members and member functions. Within a class, the data are called "data members" the functions are called "member functions"

Example: class students { int rollno; int calculate(void); };

Access Specifiers public, private, and protected Members of a class can acquire access attributes in one of two ways: by default, or through the use of the access specifiers public, private, and protected. Syntax: public: <declarations> private: <declarations> protected <declarations> Public If a member is public, it can be used by any function. In C++, members of a struct or union are public by default. Private If a member is private, it can only be used by member functions and friends of the class in which it is declared. Members of a class are private by default. Protected If a member is protected, its access is the same as for private. In addition, the member can be used by member functions and friends of classes derived from the declared class, but only in objects of the derived type. Scope Resolution Operator(::)

This operator can be used to refer to any member in the class explicitly.

Sample c++ program #include<iostream.h> // include files class student // class declarations { char name[30]; int age; public: void getdata(void); void display(void); } void student:: getdata(void) // member functions definitions { cout << "Enter name "; cin >> name; cout << "enter age" cin >> age; } void student::display(void) // member function definitions { cout << " name " << name; cout << " age " <<, age; } void main() // main function program { student s1; // s1 is an object for the class student s1.getdata(); s1.display(); }

Constructor C++ provides a special member function whose task is to initialize the objects of its class. It is special because its name is the 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. Firing of Constructor. A Constructor fires at the time of creation of objects. Types of Constructor There are 4 types of constructors. 1. Default Constructor 2. Argument or Parametric Constructor 3. Copy Constructor 4. Dynamic Constructor 1. Default Constructor : Default Constructor fires automatically at the time of creation of the objects. 2. Argumental Constructor : It fires only if the argument is passed to the constructor. 3. Copy Constructor : If the value of one constructor is given to an another constructor, then it is called as copy constructor. 4. Dynamic Construtor : It is used for allocation of memory to a variable at run time. Example : # include <iostream.h> class date { private : int dd; int mm; int yy; public :

date () // ex. for default constructor { dd=01; mm=01; yy=2002; } date (int d,int m, int y) { dd=d; mm=m; yy=y; } date(date x) { dd = x.dd; mm = x.mm; yy=x.yy; } void showdate(); void displaydate(); }; void date ::showdate() { cin >> dd>>mm>>yy; } void date ::displaydate() { cout << dd<<mm<<yy; } void main() { date d1,d2(3,3,2002); d1.showdate(); d1.displaydate(); // ex. for argumental constructor

d2.showdate(); d2.displaydate(); date (d2); } Parameterized Constructors Parameterized constructor is used to initialize the various data elements of different objects with different values when they are created. C++ permits us to achieve this objective by passing arguments to constructor function when the objects are created. The constructors that can take arguments are called parameterized constructors. Destructor A destructor, as the name implies, is used to destroy the objects that have been created by a constructor. The 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 not does it return any value. It will be invoked implicitly by the compiler upon exit from the program to clean up the storage that is no longer accessible. Example for Destructor : class word { private : char *str_word; public : word (char *s) { str_word=new char(strlen(s)); strcpy=(str_word,s); } int getlen() { return strlen(str_word); // ex for copy constructor

} char *getword() { return str_word: } ~word() { delete str_word; } }; void main() { word *word1; word1->word::~word; } Inheritance Inheritance is the process of creating new classes called derived classes, from existing or base classes. The derived class inherits all the capabilities of the base classes. The derived class inherits all the capabilities of the base class but can add embellishments and refinements of its own. The base class is unchanged by this process. Inheritance has important advantages, most importantly it permits code reusability. Once a base class is written and debugged, if need not be touched again but can nevertheless be adapted to work in different situations. Reusing existing code saves times and money and increases programs reusability. 1. Inheritance is the concept by which the properties of one entity are available to another. 2. It allocates new class to be built from older and less specialized classes instead of being rewritten from scratch. 3. The class that inherits properties and functions is called the sub class or the derived class and the class from which they are inherited is called super class (or) the base class.

4. The derived class inherits all the properties of the base class and can add properties and refinements of its own. The base class remains unchanged. # include <iostream.h> class Base { public : void show() { cout << \n Base; }}; class Der1 :public Base { public : void show() { cout <<\nDer1; } }; class Der2:public Base { public : void show() { cout <<\nDer2; } }; void main() { Der1 d1; Der2 d2; Base *ptr; Ptr=&d1; Ptr->show();

Ptr=&d2; Ptr->show(); } Function overloading This is a logical method of calling several functions with different arguments and data types that perform basically identical things by the same name. A program to demonstrate how function overloading is carried out for swapping of two variables of the various data types. #include <iostream.h> void swap(int &x, int &y); void swap(float a,float b); void main() { int x,y; float a,b; cout << Enter any two integers.. << endl; cin >> x>>y; cout << Enter any two Float numbers.. << endl; cin >> a>>b; // swapping integer numbers swap(x,y) cout << After swapping integer numbers..<<endl; cout <<x<<y; // swapping float numbers swap(a,b) cout << After swapping float numbers..<<endl; cout <<x<<y; } void swap(int &a, int &b) { int temp;

temp=a; a=b; b=temp; } void swap(float &a, float &b) { float temp; temp=a; a=b; b=temp; } Static Data Members Static member variables are similar to C static variable. A static member variable has special characteristics. It is initialized to zero when the first object of its class is created. No other initialization is permitted. Only one copy of that member is created for the entire class and is shared by all objects of that class, no matter how many objects are created. It is visible only within the class, but its lifetime is the entire program. Static variables are normally used to maintain values common to entire class. Polymorphism A property by which we can send the same message to objects of several different classes, and each respond in a different way depending on its class. We can send such message without knowing to which of the classes the objects belongs. # include <iostream.h> class date { private : int dd; int mm;

int yy; public : void showdate(); void displaydate(); }; void date ::showdate() { cin >> dd>>mm>>yy; } void date ::displaydate() { cout << dd<<mm<<yy; } void main() { date d; d.showdate(); d.displaydate(); } Virtual functions Virtual functions let derived classes provide different versions of a base class function. You can declare a virtual function in a base class, then redefine it in any derived class, even if the number and type of arguments are the same. The redefined function overrides the base class function of the same name. Virtual functions can only be member functions. You can also declare the functions int Base::Fun(int) and int Derived::Fun(int) even when they are not virtual.

The base class version is available to derived class objects via scope override. If they are virtual, only the function associated with the actual type of the object is available. With virtual functions, you can't change just the function type. It is illegal, therefore, to redefine a virtual function so that it differs only in the return type. If two functions with the same name have different arguments, C++ considers them different, and the virtual function mechanism is ignored. A function qualified by the virtual keyword. When a virtual function is called via a pointer, the class of the objects pointed to determine which function definition will be used. Virtual functions implement polymorphism, whereby objects belonging to different classes can respond to the same message in different ways. # include <iostream.h> # include <string.h> class Base { public : virtual void show_message(void) { cout <<Base class message<<,endl:}; }; virtual void show_reverse(void)=0; }; class Derived :public Base { public : virtual void show_message(void) { cout <<Derived class message<<endl; }; virtual void show_reverse(void) { cout <<strrev(Derived class message)<<endl;

} }; void main(void) { Base *poly=new Derived; Poly->show_message(); Poly->show_reverse(); } Operator Overloading C++ enables use of system defined (or standard) operators, such as +, -, *, == etc., to act on the user-defined data structures(or objects) in a way relevant to that data structure( or object). An operator thus may have the same LABEL OR SYMBOL as a structure operator, but associating with different parameters and resulting to different action. We may use the plus(+) operator on different objects. str=str1 + str2 // concatenate two strings arr=arr1 + arr2 // add two arrays c = c1 + c2 // add two complex numbers r = r1 + r2 // add two rational numbers s = s1 + s2 // union of sets s1,s2 C++ allows two variables of user-defined type with the same syntax that is applied to the basic types. C++ has the ability to provide the operators with a special meaning for a data type. The mechanism of giving such special meaning to an operator is known as Operator Overloading. The following program segment illustrates the overloading of an assignment operator in a class. #include <iostream.h>

class sample { private : int x; float y; public : sample(int, float); void operator = (sample abc); void display(); }; void sample :: operator = (sample abc) { x = abc.x; y = abc.y; } void main() { sample obj1; sample obj2; ;;;;; ;;;;; obj1 = obj2; obj2.display(); } new (operator) and delete (operator) Operators that create and destroy an object Syntax: <pointer_to_name> = new <name> [ <name_initializer> ]; delete <pointer_to_name>;

The "new" operator tries to create an object <name> by allocating sizeof(<name>) bytes in the heap. The "delete" operator destroys the object <name> by deallocating sizeof(<name>) bytes (pointed to by <pointer_to_name>). The storage duration of the new object is from the point of creation until the operator "delete" deallocates its memory, or until the end of the program. Example: name *nameptr; // name is any non-function type ... if (!(nameptr = new name)) { errmsg("Insufficient memory for name"); exit (1); } // Use *nameptr to initialize new name object ... delete nameptr; //destroy name; deallocate sizeof(name) bytes friend (keyword) A friend of a class X is a function or class that, although not a member of that class, has full access rights to the private and protected members of class X. Syntax: friend <identifier>; In all other respects, the friend is a normal function in terms of scope, declarations, and definitions. Example: class students { friend department; int rollno;

int calculate(void); }; class department { char ugcourse[25]; void performance(students*); };

Example 2 for Friend function # include <iostream.h> class Sample { int a,b; public : friend int sum(sample object); void set_ab(int i, int j); }; void sample ::set_ab(int I,int j) { a=i; b=j; } int sum(sample object) // because it is friend of a samples return object a + object b; } void main (void) { sample integer; integer.set_ab(3,4); cout <<sum(integer); } inline (keyword)

Declares/defines C++ inline functions Syntax: <datatype> <function>(<parameters>) { <statements>; } inline <datatype> <class>::<function> (<parameters>) { <statements>; } In C++, you can both declare and define a member function within its class. Such functions are called inline. The first syntax example declares an inline function by default. The syntax must occur within a class definition. The second syntax example declares an inline function explicitly. Such definitions do not have to fall within the class definition. Inline functions are best reserved for small, frequently used functions. Example: /* First example: Implicit inline statement */ int num; class cat { public: char* func(void) { return num; } char* num; } // global num

/* Second example: Explicit inline statement */ inline char* cat::func(void) { return num; } operator (keyword) Defines a new action

Syntax: operator <operator symbol>( <parameters> ) { <statements>; } The keyword "operator", followed by an operator symbol, defines a new (overloaded) action of the given operator. Example: complex operator +(complex c1, complex c2) { return complex(c1.real + c2.real, c1.imag + c2.imag); } this (C++ keyword) Non-static member functions operate on the class type object with which they are called. For example, if x is an object of class X and func is a member function of X, the function call x.func() operates on x. Similarly, if xptr is a pointer to an X object, the function call xptr->func() operates on *xptr. But how does func know which x it is operating on? C++ provides func with a pointer to x called "this". "this" is passed as a hidden argument in all calls to non-static member functions. The keyword "this" is a local variable available in the body of any nonstatic member function. The keyword "this" does not need to be declared and is rarely referred to explicitly in a function definition. However, it is used implicitly within the function for member references. For example, if x.func(y) is called, where y is a member of X, the keyword "this" is set to &x and y is set to this->y, which is equivalent to x.y. Virtual Classes

You might want to make a class virtual if it is a base class that has been passed to more than one derived class, as might happen with multiple inheritance. A base class can't be specified more than once in a derived class: class B { ...}; class D : B, B { ... }; // ILLEGAL However, a base class can be indirectly passed to the derived class more than once: class X : public B { ... } class Y : public B { ... } class Z : public X, public Y { ... } // OK In this case, each object of class Z will have two sub-objects of class B. If this causes problems, you can add the keyword "virtual" to a base class specifier. For example, class X : virtual public B { ... } class Y : virtual public B { ... } class Z : public X, public Y { ... } B is now a virtual base class, and class Z has only one sub-object of class B. Constructors for Virtual Base Classes Constructors for virtual base classes are invoked before any non-virtual base classes. If the hierarchy contains multiple virtual base classes, the virtual base class constructors are invoked in the order in which they were declared. Any non-virtual bases are then constructed before the derived class constructor is called. If a virtual class is derived from a non-virtual base, that non-virtual base will be first, so that the virtual base class can be properly constructed. For example, this code

class X : public Y, virtual public Z X one; produces this order: Z(); // virtual base class initialization Y(); // non-virtual base class X(); // derived class Function Definition and Prototyping The compiler must be informed of the return types and parameter types of the functions so that it will be able to check for the correct usage of the calls to those functions during compilation. To satisfy the compiler either of the following conventions may be adapted: 1. A complete function definition #include< iostream.h> int triple(int); // function prototype void main() { cout<<\n The tripled value of f is <<triple(25); } int triple(int f) { return (f * f * f); } 2. A declaration of the function prototype before the function call. Float square(float); or float square(float x); Int main(void)

{ printf(%f\n,square(5.0)); } /* A simple C++ program to demonstrate the use of function prototype */ #include<iostream.h> float square(float); void print(float); int main(void) { float x; x=square(25.0); print(x); } /* Actual definition of the function */ float square(float x) { return(x*x); } void print(float x) { cout<<x; } Some conventions in specifying default initializers 1. Multiple default initializers and their order: Multiple parameters may be given default values, but these must be assigned from the rightmost parameter to the left. 2. Default initializers and prototype definitions:

By convention, default initializes can occur only in the prototype definitions, not in the actual function definitions. Eg. int power(int exponent, int base=2);// This prototype definition is correct// int power(int exponent, int base=2); // Not correct// { /* function code */ } 3. No repetition of default intializer: A default intializer can occur only once. Assume that myfunc.h contains the following prototype definition: Int power(int exponent, int base=2); Then, #include myfunc.h// myfunc.h has original definition int power(int exponent, int base=2) // Illegal, base is given with a default value// 4. Successive default initialization : Applications can use this convention to customize the default initialization according to their requirement. The following cases show legal and illegal successive declarations. Case 1: int power(int exponent, base); // Original declaration int power(int exponent, base=2); // legal(successive) redeclaration// int power(int exponent=0, base); // legal(successive) redeclaration// Case 2: int power(int exponent, base); // Original declaration

int power(int exponent=0, base); // Illegal, start from rightmost redeclaration // int power(int exponent=0, base=2); // Illegal, exponent already initialized // Case 3: int power(int exponent, base=2); // Original declaration int power(int exponent, base); // Legal redeclaration int power(int exponent=0, base); // Legal redeclaration TEMPLATE A Template provides the formats of functions and type placeholder. It eliminates duplication of functions and datas. The following shows the general forms of a function template, where T is a type that the compiler will later replace. Template<class T> T function_name(T param_1, T param_b) { // statements } for example template<class T> T compare_values(T a,T b) { return(a+b); } The complier can replace the letter T with either the type float or int. Function Template The function template acts as model and it can be replaced by any type of function data types.

Simple Example: #include <iostream.h> template<class T > T add(T a, T b) { T c; c=a+b; return(c); } void main() { int a,b; float c,d; cin>>a>>b; cout<<add(a,b); cout<<add(c,d); }

Generic Template: A generic function defines a general set of operations that the function will apply to various data type. A generic function receives the type of data on which the function will operate as a parameter. Creating generic functions within our program can be useful because many algrorithms are fundamentally the same in their processing yet independent of the data type on which the algorithm operates. The word template is a key and T type is place holder of the data type. template <class T type> return type function name(parameter list) { //statement } #include <iostream.h> template<class T, class T1 > T avg(T a, T b) {

T1 c; c=(a+b)/2; return(c); } void main() { int a,b; float c; cin>>a>>b; c=avg(a,b); cout<<c; } Class Template: If a class acts a placeholder for nay data type then the class must be defined in the form of template. template <class T> class someclass { //statement ; } Here the template not only specifies a type placeholder , it also specifies a parameter that the program can use within the template. When the program later uses the template, it can pass a parameter value to the template as shown here Someclass<int 1029> this_instance template <class T> class add { T a; T b; public: void sum(); void getdata(); }; template <class T>void add<T>::sum()

{ T c; c=a+b; cout<<c; } template <class T>void add<T>::getdata() { cin>>a>>b; } void main() { add a; a.getdata(); a.sum() }

OBJECTS AND CLASSES

Object Oriented Programming Concepts Objects - Classes Methods and Messages Abstraction and Encapsulation Inheritance Abstract Classes Polymorphism Basics of C++ Classes Access Specifiers Function and Data Members Default Arguments Function Overloading Friend Functions Const and Volatile Functions

Static Members Objects - Pointers and Objects Constant Objects Nested Classes Local Classes

1.1. Object Oriented Programming Concepts This programming approach is developed to reduce the some of the drawbacks encountered in the Procedure Oriented Programming Approach. The OO Programming approach treats data as critical element and does not allow the data to freely around the program It bundles the data more closely to the functions that operate on it; it also protects data from the accidental modification from outside the function. The object oriented programming approach divides the program into number of entities called objects and builds the data and functions that operates on data around the objects. The data of an object can only access by the functions associated with that object.

1.1.1. Benefits or Advantages of OOPS The complexity of software can be managed easily. Data hiding concept help the programmer to build secure programs Through the class concept we can define the user defined data type. The inheritance concept can be used to eliminate redundant code The message-passing concept helps the programmer to communicate between different objects. New data and functions can be easily added whenever necessary. OOPS ties data elements more closely to the functions that operates on.

1.1.2. Objects When you approach a programming problem in an object-oriented language, you no longer ask how the problem will be divided into functions, but how it will be divided into objects. Thinking in terms of objects, rather than functions, has a surprisingly helpful effect on how easily programs can be designed. This results from the close match between objects in the programming sense and objects in the real world.

Physical objects Automobiles in a traffic-flow simulation Electrical components in a circuit-design program Countries in an economics model Aircraft in an air-traffic-control system Elements of the computer-user environment Windows Menus Graphics objects (lines, rectangles, circles) The mouse, keyboard, disk drives, printer Data-storage constructs Customized arrays Stacks Linked lists Binary trees Human entities Employees Students Customers Salespeople Collections of data An inventory A personnel file A dictionary A table of the latitudes and longitudes of world cities User-defined data types Time Angles Complex numbers Points on the plane Components in computer games Cars in an auto race Positions in a board game (chess, checkers) Animals in an ecological simulation Opponents and friends in adventure games 1.1.3. Classes

In OOP we say that objects are members of classes. What does this mean? Lets look at an analogy. Almost all computer languages have built-in data types. For instance, a data type int, meaning integer, is predefined in C++. You can declare as many variables of type int as you need in your program: int day; int count; int divisor; int answer; In a similar way, you can define many objects of the same class A class serves as a plan, or template. It specifies what data and what functions will be included in objects of that class. Defining the class doesnt create any objects, just as the mere existence of data type int doesnt create any variables. 1.1.4. Methods (Functions) and Messages A function groups a number of program statements into a unit and gives it a name. This unit can then be invoked from other parts of the program. The most important reason to use functions is to aid in the conceptual organization of a program. Another reason to use functions (and the reason they were invented, long ago) is to reduce program size. Any sequence of instructions that appears in a program more than once is a candidate for being made into a function. The functions code is stored in only one place in memory, even though the function is executed many times in the course of the program. Figure shows how a function is invoked from different sections of a program. 1.1.5. Passing Arguments to Functions (Messages) An argument is a piece of data (an int value, for example) passed from a program to the function. Arguments allow a function to operate with different values, or even to do different things, depending on the requirements of the program calling it. 1.1.6. Abstraction and Encapsulation Inheritance The idea of classes leads to the idea of inheritance. In our daily lives, we use the concept of classes as divided into subclasses. We know that the class of animals is divided into

mammals, amphibians, insects, birds, and so on. The class of vehicles is divided into cars, trucks, buses, and motorcycles. The principle in this sort of division is that each subclass shares common characteristics with the class from which its derived. Cars, trucks, buses, and motorcycles all have wheels and a motor; these are the defining characteristics of vehicles. In addition to the characteristics shared with other members of the class, each subclass also has its own particular characteristics: Buses, for instance, have seats for many people, while trucks have space for hauling heavy loads. An OOP class can be divided into subclasses. In C++ the original class is called the base class; other classes can be defined that share its characteristics, but add their own as well. These are called derived classes. Abstract classes Classes used only for deriving other classes are called abstract classes. It is meaning that no actual instances (objects) of this class are created. However, the term abstract has a more precise definition when using virtual function. Polymorphism Using operators or functions in different ways, depending on what they are operating on, is called polymorphism (one thing with several distinct forms). When an existing operator, such as + or =, is given the capability to operate on a new data type, it is said to be overloaded. Overloading is a kind of polymorphism; it is also an important feature of OOP. 1.2. Basics of C++ C++ was developed by BJARNE STROUSSTRUP at AT&T BELL Laboratories in Murry Hill, USA in early 1980s. Strousstrup combines the features of C language and SIMULA67 to create more powerful language that support OOPS concepts, and that language was named as C with CLASSES. In late 1983, the name got changed to C++. The idea of C++ comes from C language increment operator (++) means more additions.

C++ is the superset of C language, most of the C language features can also applied language. to C++, but the object oriented features (Classes, Inheritance, Polymorphism, Overloading) makes the C++ truly as Object Oriented Programming

1.2.1. Structure of C++ Program

Include files provides instructions to the compiler to link functions from the system library. Eg: #include <iostream.h> #include Preprocessor Directive iostream.h Header File A class is a way to bind and its associated functions together. defined datatype. It must be declared at class declaration part. Member function definition describes how the class functions are implemented. This must be the next part of the C++ program. Finally main program part, which begins program execution. main( ) {} Program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function is the logical and of the program. 1.2.2. Input / Output statements Input Stream Syntax: cin >> var1 >> var2 >>; It is a user

cin Keyword, it is an object, predefined in C++ to correspond to the standard input stream. >> - is the extraction or get from operator Extraction operation (>>) takes the value from the stream object on its left and places it in the variable on its right. Eg: cin>>x; cin>>a>>b>>c; Output Stream: Syntax: cout<<var1<<var2; cout - object of standard output stream << - is called the insertion or put to operator It directs the contents of the variable on its right to the object on its left. Output stream can be used to display messages on output screen. Eg: cout<<a<<b; cout<<value of x is<<x; cout<<Value of x is<<x<<less than<<y; 1.2.2. Tokens The smallest individual units in a program are known as tokens. C++ has the following tokens Keywords Identifiers Constants Strings Operators 1.2.3.1. Keywords

It has a predefined meaning and cannot be changed by the user Keywords cannot be used as names for the program variables.

Keywords supported by C++ are:

The specific C++ Keywords asn catch class delete friend inline 1.2.3.2. Identifiers Identifiers refer to the names of variables, functions, arrays, classes, etc. created by the programmer. Rules for naming these identifiers: 1. Only alphabetic characters, digits and underscores are permitted. 2. The name cannot start with a digit. 3. Uppercase and lowercase letters are distinct. 4. A declared keyword cannot be used as a variable name. (i) Variables: It is an entity whose value can be changed during program execution and is known to the program by a name. A variable can hold only one value at a time during program execution. new operator private protected public template this throw try virtual

Declaration of Variables Syntax datatype variablename; Datatype It is the type of data, that is going to be processed within the program

Eg: int x; float y,z; char a; A variable can be declared anywhere in the program before its first use.

1.2.3.3. Constants A quantity that does not change is known as constants. Types of constants: Integer constants Real constants - E.g. 123, 25 without decimal point - E.g. 12.3, 2.5 - with decimal point

Character constants - E.g. A, B, *, 1

1.2.3.4. Strings A sequence of characters is called string. String constants are enclosed in double quotes as follows Hello 1.2.3.5. Operators An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Types of Operators 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Assignment Operators 5. Increment & decrement Operators 6. Conditional Operators 7. Bitwise Operators 8. Special Operators 9. Manipulators 10. Memory allocate / delete Operators An expression is a combination of variables, constants and operators written according to the syntax of the language. Precedence of Operators

1.6 Manipulators Manipulators are operators used to format the data display. manipulators are endl, setw.

The commonly used

endl manipulators

It is used in output statement causes a line feed to be inserted, it has the same effect as using the newline character \n in C language. #include <iostream.h> main() { int a=10, b=20; cout << C++ language << endl; cout << A value: << a << endl; cout << B value: << b << endl; } O/P: C++ language A value: 10 B value: 20

setw Manipulator

The setw manipulator is used or specify the field width for printing, the content of the variable. Syntax: setw(width); where width specifies the field width. int a = 10; cout << A value << setw(5) << a << endl; Output: A value

10

Symbolic Constant

Symbolic constants are constants to which symbolic names are associated for the purpose of readability and ease of handling. #define preprocessor directive const keyword enumerated data type

#define preprocessor directive It associates a constant value to a symbol and is visible throughout the function in which it is defined. Syntax: #define symbol name constant value Eg #define max_value 100 #define pi 3.14 The value of symbolic constant will not change throughout the program. const keyword Syntax: const datatype var = constant; E.g.: const int max = 100; main() { char x[max]; ----------------} const size = 10; Allowable statement, default symbolic constant type is integer. Here size is of type int. Reference Variable: A reference variable provides an alias (alternative name) for a previously defined variable. For example, if we make the variable sum a reference to the variable total, then sum & total can be used interchangeably to represent that variable. A reference variable is created as follows: datatype & ref_name = var_name; Eg: float total = 100; float & sum = total; cout << sum << total; Both the variables refer to the same data object in the memory i.e. total, sum 100

1.7. Type Conversion: (i) (ii) Implicit type conversion Explicit type conversion

Implicit type conversion It will be done by the compiler, by following the rule of lower type converted to higher type. Eg: int y = 10; float z = 10.5,x; x = y+z; (y is converted to float type by compiler) x = 10.0 + 10.5 x= 20.5 (result var. x is must be float)

Explicit type conversion It will be performed by the programmer according to the need of this in the program. Syntax: Eg: datatype (var)

int y = 10; float z = 2.5; (resultant type of y+z is float, that is converted explicitly to int type) x = int (y + z);

Now the result is of int type. The following Statements are supporting to construct selection control instructions: 1. 2. 3. 4. simple if statement if-else statement Nested if- else statement Else-if statement

The following Statements are supporting to construct loop control instructions: 1. while statement 2. do - while statement 3. for statement

1.8. JUMPING STATEMENTS BREAK Statement We often come across situations where we want to jump out of a loop instantly, without waiting to get back to the conditional test. The keyword break allows us to do this. It is used to terminate the loop. When the keyword break is used inside any c++ loop, control automatically transferred to the first statement after the loop. A break usually associated with if statement. Syntax : break;

CONTINUE Statement In some programming situation we want to take the control to the beginning of the loop, by passing the statement inside the loop, which have not yet been executed. The keyword continue allows us to do this. When the keyword continue is encountered inside a c++ loop, control automatically passes to the beginning of the loop Continue statement usually associated with if statement. Syntax: continue;

Unconditional statement goto is the unconditional statement. Which is used to move the control anywhere inside the program. Goto require a lable in order to identify the place where the control is to be moved. A label is a valid variable name & a colon must follow it. The label is placed immediately before the statement where the control is to be transferred. General form: goto label; 1.9. CASE CONTROL INSTRUCTION The control statement, which allows user to make a decision from the number of choices, is called a switch case statement. It allows user to execute a group of statements from several available group of statements.

Syntax: switch( expression) { case value1: block1; break; case value2: block1; break; case value3: block1; break; default: deafult block; } statement x;

Rules to be followed to construct case control instructions 1. 2. 3. 4. 5. The expression in switch statement must be an integer value or a No case values are identical Each case block must end with break statement. The case keyword must terminate with colon(:) Default is optional. character constant.

1.10. FUNCTIONS It is difficult to implement a large program even if it is algorithm is available. To implement such a program in an easy manner, it should be split into a number of independent tasks, which can be easily designed, implemented, and managed. This process of splitting a large program into small manageable tasks and designing them independently is called Modular Programming. A repeated group of instruction in a program can be organized as a function. A function is a set of program statements that can be processed independently. Advantages Reduction in the amount of work and development time. Program and function debugging is easier. Reduction in size of the program due to code Reusability.

Function Components Function declaration or prototype Function Definition Function call Function parameters Function return statement

i. Function Prototype or Declaration: It provides the following information to the compiler The name of the function The type of the value returned (optional, default is an integer) The number and type of the arguments that must be supplied in a call to the function. Syntax: Return type function_name(argu1,argu2,argun); Return type Fun_name specifies the data type of the value in the return statement. name of the function. type of argument to be passed from calling function to Argu1,argu2argun Examples: int max(int,int); It informs the compiler that the function max has 2 arguments of the type integer. The function max() returns an integer values. void max(); It informs the compiler that the function max has no arguments, max() is not returning any value. max(); It informs the compiler that the function max has no arguments.

the called function

The function max() returns an integer values. In function prototype default return type is integer.

ii. Function definition: The function itself is referred to a function definition. Syntax:

return type function_name(argu1,argu2,argun) //function declarator { function body; } The first line of the function definition is known as function declarator, and is followed by the function body. The function delcarator and declaration must use the same function name, the number of arguments, the arguments type and the return type. Function definition is allowed to write in a program either above or below the main (). If the function is defined before main (), then function declarator is optional. Example: int max(int x, int y) { if(x>y) return(x); else return(y); }

For this function max() definition, it is declaration must be : int max(int,int); iii. Function call: A function, which gets life only when a call to the function is made. A function call specified by the function name followed by the arguments enclosed in parenthesis and terminated by a semi colon. Syntax: Function_name(argu1,argu2,argun) ; If a function contains a return type the function call is of the following form: var= Function_name(argu1,argu2,argun) ; Example: c=max(a,b); iv. Function Parameters The parameters specified in the function call are known as actual parameters and those specified in the function declarator (definition) are known as formal parameters

For example in the main(), the statement c=max(a,b); passes the parameters(actual parameters) a and b to max().

The parameters x and y are formal parameters. When a function call is made, a one to one correspondence is established between the actual and the formal parameters.

The scope of the formal parameters is limited to its function only.

v. Function Return Functions can be grouped into two categories: i. A Function does not have a return value (void function) ii. Functions that have a return value. The statements: return(x); and return(y);in function max() are called function return statements. The caller must be able to receive the value returned by the function. In the statement c=max(a,b) , The value returned by the function max() returning a value to the caller. Limitation of return A key limitation of the return statement is that it can be used to return only one item from a function. Passing Data To Functions The entity used to convey the message to a function is the function argument. It can be a numeric constant, a variable, multiple variables, user defined data type, etc. Passing constants as arguments The following program illustrates the passing of a numeric constant as an argument to a function. This constant argument is assigned to the formal parameter which is processed in the function body. // Greatest among 2 numbers #include<iostream.h> void main() { int a,b; int max(int,int); //function declaration

int c= max(40,35); cout<<Greatest is: <<c; } int max(int x,int y) { if (x>y) return(x); else return(y); } Run: Enter any 2 integers 40 35 Greatest is: 40 In main(), the statement c=max(40,35); invoke the function max with the constants. Passing variable as arguments Similarly to constants, varables can also be passed as arguments to a function. // Greatest among 2 numbers #include<iostream.h> void main() { int a,b; int max(int,int); //function declaration cout<<enter two integer ; cin>>a>>b; int c= max(a,b); cout<<Greatest is: <<c; } int max(int x,int y) { if (x>y) return(x); else return(y); } Run: Enter any 2 integers 40 Greatest is: 40 In main(), the statement c=max(a,b); invoke the function max with the values of a & b

Parameter Passing Parameter passing is a mechanism for communication of data and information between the calling function and the called function. It can be achieved by either by passing values or address of the C++ supports the following 3 types of parameter passing schemes: 1. Pass by Value 2. Pass by Address 3. Pass by Reference i. Pass by Value The default mechanism of parameter passing is called pass by value. Pass by value mechanism does not change the contents of the argument variable in the calling function, even if they are changed in the called function. Because the content of the actual parameter in a calling function is copied to the formal parameter in the called function.Changes to the parameter within the function will affect only the copy (formal parameters) and will have no effect on the actual argument. ii. Pass by Address: C++ provides another means of passing values to a function known as pass by address mechanism. Instead of passing the value, the address of the variable is passed. In function, the address of the argument is copied into a memory location instead of the value. Example: #include<iostream.h> void swap(int *x,int *y) { int t; t=*x; *x=*y; *y=t; } void main() { int a,b; variable.

cout<<enter two integers; cin>>a>>b; swap(&a,&b); cout<<value of a and b after calling swap() in main(); cout<<a<<setw(5)<<b; } Run: enter two integers 30 50 value of a and b after calling swap() in main(); 50 30 iii. Pass by Reference Passing parameters by reference has the functionality of pass by address and the syntax of pass by value. Any modification made through the formal parameter is also reflected in the actual parameter. To pass as argument by reference, the function call is similar to that of call by value. In function declarator, those parameters, parameters, which are to be received by reference, must be preceded by the address ( & )operator. The reference type formal parameters are accessed in the same way as normal value parameters. However, any modification to them will also be reflected in the actual parameter Example: #include<iostream.h> void swap(int &x,int &y) { int t=x; x=y; y=t; } void main() { int a,b; cout<<enter two integers; cin>>a>>b; swap(a,b); cout<<value of a and b after swap(a,b) in main(); cout<<a<<setw(5)<<b; }

Run: enter two integers 30 50 value of a and b after swap(a,b) in main() 50 30 1.11. Default Arguments Normally a function should specify all the arguments used in the function definition. In a c++ function call, when one or more arguments are omitted, the function may be defined to take default values for the omitted arguments by providing the default values in the function prototype. Hence the feature of default arguments allows the same function to be called with fewer arguments than defined in the function prototype. To establish a default value, the function declaration must be used. The compiler checks the function prototype with the arguments in the function call to provide default values to those arguments, which are omitted. Default arguments reduce the burden of passing arguments explicitly at the point of the function call. Example: #include<iostream.h> void greatest(int = 50;int=25,int =35); void main() { greatest(); greatest(10); greatest(75,12); greatest(15,2,55); }

1.12. Inline functions One of the objectives of using functions in a program is to save memory, which becomes appreciable when a function is likely to be called many times. However, every time a function is called, it takes a lot of extra time in executing a series of instructions, for task such as jumping to the function, and returning to the calling function. When a function is small, the time required to execute a function is less than the switch time.

In C++ a new feature called inline function is used to solve the above problem. An inline function is a function that is expanded in line when it is called. That is, the compiler replaces the function call with the corresponding function code. Inline functions are defined as follows inline return type fun_name(arguments) { function body } Example inline double cube(double a) { return(a*a*a); }

1.13. Function Overloading It is possible to define several functions having the same name, but performing different actions. It helps in reducing the need for unusual function name, making the code easier to read. This can be done using the concept Function polymorphism or function overloading. Function overloading allows multiple functions to share the same name with different argument type. Function Polymorphism implies that the function definition can have multiple forms. The definitions must only differ in number of arguments and types of arguments. Example: //Multiple swap functions #include<iostream.h> void swap(char x, char y) { char t=x; x=y; y=t; cout<<Swapped characters<<x<<setw(5)<<y; } void swap(int x, int y) { int t=x; x=y; y=t; cout<<Swapped integers<<x<<setw(5)<<y; }

1.13. Recursive Function A function that contain a function call to itself, or a function call to a second function which eventually calls the first function is known as a recursive function. In other words a function which calls itself It is used to solve the recurrence relations. One important condition must be satisfied by any recursive function are: There must be decision criteria for stopping the process or computation. It involves the overhead of saving the return address, formal parameters, local variables upon entry & restore these parameters and variables on completion. Example: Factorial of a number: Fact(n)={ 1 if n=0; #include<iostream.h> void main() { int num; long int fact(int); //prototype cout<< Ener the no, whose factorial is to be found; cin>>num; long int f=fact(num); cout<< factorial of << num <<is<<f; } long int fact (int n) { long int fa; if (n==0) fa=1; else fa=fa*fact(n-1); return(fa): } Run: Enter the no, whose factorial is to be found 5 factorial of 5 is 120

1.14. Classes The objects with the same data structure (attribute) and behaviour (operations) are grouped into a class. All these objects possessing similar properties are grouped into the same unit. Eg: In the person class all person having similar attributes like Name, Age, Sex and the similar operations like speak, listen, walk. So, boy and girls objects are grouped into the person class. Representation of Class: Class account private: { char name[20]; int accounttype; int accountnumber; float balance; Deposit( ); Withdraw( ); Enquire( );

public: };

In this the account class groups the object such as saving account, current account, etc, Thus, objects having the same structural and behavioral propositions are grouped together to form a class. The following points on classes can be noted: 1. A class is a template that unites data and operations. 2. A class is a abstraction of the real world entities with similar properties. 3. A class identifies a set of similar objects. Classes and Objects: Class Specification: The class can be described as a collection of data member along with member functions. This property of C++, which allows association of data and functions into a Sometimes classes may not contain any data single unit, is called encapsulation.

members or member function called empty classes.

Syntax for class specification

More than one object can be created with a single statement as, Class student s1,s2,s3; Or Student s1,s2,s3. Object can also be created by placing these names immediately after the closing brace. Thus the definition Class student { ----------------------------} s1,s2,s3; 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(.). Syntax: for accessing datamember of a class

Syntax for accessing member function of a class

Defining Member Function The data members of a class must be declared within the body of the class, whereas the member functions of the class can be defined in any one of the following ways. Inside the class specification

Outside the class specification

The syntax of a member function definition changes depending on whether it is defined inside or outside the class specification, but it performs the same operation. (a) Member function inside the class body: (b) Member functions outside the class body Data Hiding: Data is hidden inside a class, so the unauthorized access is not possible, which is the key feature of OOP. All the data and functions defined in a class are private by default. Methods of Data hiding Private Public Protected

Access Specifiers Private members: In this only the member functions of the same class can access these members. The private members of a class are inaccessible outside the class. class person { private: int age; //private data int getage( ): //private function ... . } person p1; a = p1.age; //cannot access private data //error p1.getage( ); //Error access i.e., we can access the private members by using objects. Protected member The access control of the protected members is similar to that of private members. The access control of protected members is shown below: Class person

{ protected: ... . int age; // protected data int getage( ): //protected function ... . }; person p1; // Cannot access protected members a = p1.age; p1.getage( ); Public Members All data members and function declared in the public section of the class can be accessed without any restriction from anywhere in the program. Eg: class person { public: int age; //public data int getage( ); //public function } person p1; a = p1.age; // can access public data p1.getage( ); // can access public function 1.15. Function and Data Members A member function of a class can be called only by an object of that class using a dot operator. In nesting of member function, the member function can be called by using its name inside another member function of the same class is called nesting member function. Arrays within a class The arrays can be used as member variables in a class. That is more than one related variable or data are grouped under the common name, Eg: Class abc { int a[size]; //a is name of the array size represents the size of the array public: void setdata(void); void display(void);

}; Empty classes (or Stubs) Main reason for using a class is to encapsulate data and code, it is however, possible to have a class that has neither data nor code. In other words, it is possible to empty classes. The declaration of empty classes is as follows: class xyz { }; class abc { }; Such an empty classes are also called as stubs Passing Objects Arguments It is possible to have functions which accept objects of a class as arguments, just as there are functions which accept other variables as arguments. An object can be passed as an argument to a function by the following ways: 1. 2. 3. Passing object by value, a copy of the entire object is passed to the function Passing object by reference, only the address of the object is passed implicitly to the function. Passing object by pointer, the address of the object is passed explicitly to the function Passing Object by value In this case a copy of the object is passed to the function and any modifications made to the object inside the function are not reflected in the object used to call the function. Example: #include<iostream.h> class test { int m1,m2; public: void get() { cin>>m1>>m2; }

void read(test t3) { m1=t3.m1; m2=t3.m2; } void display() { cout<<m1<<m2; } }; void main() { test t1; cout<<Enter Ist object data; t1.get(); cout<<display Ist object data; t1.display(); test t2; cout<<copy of object1 to object2; t2. read(t1); cout<<display 2nd object data; t2.display(); } Run: Enter Ist object data 34 56 display Ist object data 34 56 copy of object1 to object2 display 2nd object data 34 56 The members of t1 are copied to t2. Any modification made to the data members of the objects t1 and t2 are not visible to the callers actual parameter Passing objects by Reference Accessibility of the objects passed reference is similar to those passed by value. Modifications carried out on such objects in the called function will also be reflected in the calling function. Example: #include<iostream.h> class test { int m1,m2; public: void get() {

cin>>m1>>m2; } void read(test &t3) { m1=t3.m1; m2=t3.m2; } void display() { cout<<m1<<m2; } }; void main() { test t1; cout<<Enter Ist object data; t1.get(); cout<<display Ist object data; t1.display(); test t2; cout<<copy of object1 to object2; t2. read(t1); cout<<display 2nd object data; t2.display(); } Run: Enter Ist object data 34 56 display Ist object data 34 56 copy of object1 to object2 display 2nd object data 34 56

UNIT II - CONSTRUCTORS AND DESTRUCTORS (9)

Constructors Default Constructor Parameterized Constructors Constructor with Dynamic Allocation Copy Constructor Destructors Operator Overloading Overloading through Friend Functions Overloading the Assignment Operator Type Conversion Explicit Constructor

2.1. CONSTRUCTOR Constructor is a special member function. This is used to give initial values to member variables. The general form is: constructor_name(parameters) { statements to give initial values to member variables Rules: It should be declared as public. No return type needed. When the object is declared for the class, it automatically executes the constructor and initialized the variables. }

There are two types of constructors. They are: 1. Constructor without parameters 2. Constructor with parameters (or) parameterized constructor 2.1.1. Constructor without parameters If a constructor has no arguments then it is called constructor without parameters. #include <iostream> #include <iostream.h>

#include <conio.h> class myclass { int a,b; public: myclass(); // constructor ~myclass(); // destructor void show(); }; myclass::myclass(){ cout << "In constructor\n"; a = 10; b = 20; } void myclass::show() { cout << "A =" << a << endl << "B =" << b << endl; cout << "Sum is " << a+b << endl; } void main() { clrscr(); myclass ob; ob.show(); } 2.1.2. Constructor with parameters (or) parameterized constructor If a constructor has arguments then it is called parameterized constructor. The value of the arguments should be given along the object declaration. The general form is: Classname object( argument_list ); (or) Classname object = classname(argument_value_list); Example: #include <iostream> #include <iostream.h> #include <conio.h> class myclass { int a,b; public: myclass(int x, int y); // constructor ~myclass(); // destructor void show(); }; myclass::myclass(int x, int y) { cout << "In constructor\n"; a = x;

b = y; } void myclass::show() { cout << "A =" << a << endl << "B =" << b << endl; cout << "Sum is " << a+b << endl; } void main() { clrscr(); myclass ob(10,20); ob.show(); } Possible questions: 1. 2. 3. 4. 5. Define constructor. Define default constructor. Define parameterized constructor. Define default argument constructor. What is the ambiguity between default constructor and default argument constructor?

1. Discuss about various types of constructors in detail. Give some examples. 2.2. Multiple Constructor (or) Constructor Overloading

If a class has more than one constructor, then it is called multiple constructors. This technique is called overloading constructors, because all constructors have the same name and they differ only in the number of arguments or data types. Example: #include<iostream.h> #include<conio.h> class con { int c; public: con(); con(int x); con(int x,int y); con(int x,int y,int z); }; con ::con() { c=0; cout<<"\n\n\t Result is :\t"<<c; } con ::con(int x) { c=x*x;

cout<<"\n\n\t Result is :\t"<<c; } con::con(int x,int y) { c=x*y; cout<<"\n\n\t Result is :\t"<<c; } con ::con(int x,int y,int z) { c=x*y*z; cout<<"\n\n\t Result is :\t"<<c; } void main() { clrscr(); cout<<"\n\n\t OUTPUT:\n"; con c; con s(3); con s1(3,5); con s2(3,2,2); getch(); } Possible questions: 1. Define multiple constructors. 2. Define dynamic constructor. 1. Discuss about the constructor overloading in detail. Give an example to implement it. 2.3. Constructor with default arguments If we give initial values to the member variables inside the argument list of constructor then it is called constructor with default arguments. The general form is: constructor_name (return_type variable1= value1, return_type variable2= value2, . return_type variable n= value n { member_variable1 = variable1; member_variable2 = variable2 .. member_variable n = variable n; } At the time of object declaration, depending upon the value, the constructor automatically assign the values to member variables. If any value is missing this will be taken from the argument list values.

Example: #include <iostream> #include <iostream.h> #include <conio.h> class myclass { int a,b; public: myclass(int x, int y); // constructor ~myclass(); // destructor void show(); }; myclass::myclass(int x = 30, int y = 40){ cout << "In constructor\n"; a = x; b = y; } void myclass::show() { cout << "A =" << a << endl << "B =" << b << endl; cout << "Sum is " << a+b << endl; } void main() { clrscr(); myclass ob1(10,20); myclass ob2(5); ob1.show(); ob2.show(); } Output: A = 10 B = 20 Sum is 30 A=5 B = 40 Sum is 45 Possible questions: 1. Define default argument constructor. 2. What is the ambiguity between default constructor and default argument constructor? 1. Explain about Data Handling and member function. Explain copy constructor and destructor with suitable C++ coding . 2. Discuss about the constructor overloading in detail. Give an example to implement it. 3. Discuss about various types of constructors in detail. Give some examples.

2.3. Operator Overloading An operator function defines the operations that the overloaded operator will perform relative to the class upon which it will work. An operator function is created using the keyword operator. Creating a Member Operator Function A member operator function takes this general form: ret-type class-name::operator#(arg-list) { // operations } The # is a placeholder. When you create an operator function, substitute the operator for the #. For example, if you are overloading the / operator, use operator/. When you are overloading a unary operator, arg-list will be empty. When we are overloading binary operators, arg-list will contain one parameter. Example: #include <iostream> using namespace std; class loc { int longitude, latitude; public: loc() {} loc(int lg, int lt) { longitude = lg; latitude = lt; } void show() { cout << longitude << " "; cout << latitude << "\n"; } loc operator+(loc op2); }; // Overload + for loc. loc loc::operator+(loc op2) { loc temp; temp.longitude = op2.longitude + longitude; temp.latitude = op2.latitude + latitude; return temp; } int main()

{ loc ob1(10, 20), ob2( 5, 30); ob1.show(); // displays 10 20 ob2.show(); // displays 5 30 ob1 = ob1 + ob2; ob1.show(); // displays 15 50 return 0; } Here the operator+() function returned some other type, this expression would not have been valid: ob1 = ob1 + ob2; In order for the sum of ob1 and ob2 to be assigned to ob1, the outcome of that operation must be an object of type loc. 2.4. Operator Overloading Using a Friend Function Since a friend function is not a member of the class, it does not have a this pointer. Therefore, an overloaded friend operator function is passed the operands explicitly. This means that a friend function that overloads a binary operator has two parameters, and a friend function that overloads a unary operator has one parameter. When overloading a binary operator using a friend function, the left operand is passed in the first parameter and the right operand is passed in the second parameter. In this program, the operator+() function is made into a friend: #include <iostream> using namespace std; class loc { int longitude, latitude; public: loc() {} // needed to construct temporaries loc(int lg, int lt) { longitude = lg; latitude = lt; } void show() { cout << longitude << " "; cout << latitude << "\n"; } friend loc operator+(loc op1, loc op2); // now a friend loc operator-(loc op2); loc operator=(loc op2); loc operator++(); }; // Now, + is overloaded using friend function. loc operator+(loc op1, loc op2) {

loc temp; temp.longitude = op1.longitude + op2.longitude; temp.latitude = op1.latitude + op2.latitude; return temp; } // Overload - for loc. loc loc::operator-(loc op2) { loc temp; // notice order of operands temp.longitude = longitude - op2.longitude; temp.latitude = latitude - op2.latitude; return temp; } // Overload assignment for loc. loc loc::operator=(loc op2) { longitude = op2.longitude; latitude = op2.latitude; return *this; // i.e., return object that generated call } // Overload ++ for loc. loc loc::operator++() { longitude++; latitude++; return *this; } int main() { loc ob1(10, 20), ob2( 5, 30); ob1 = ob1 + ob2; ob1.show(); return 0; } There are some restrictions that apply to friend operator functions. First, you may not overload the =, ( ), [ ], or > operators by using a friend function. Second, as explained in the next section, when overloading the increment or decrement operators, you will need to use a reference parameter when using a friend function. 2.5. Using a Friend to Overload ++ or If we want to use a friend function to overload the increment or decrement operators, you must pass the operand as a reference parameter. This is because friend functions do not have this pointers. #include <iostream> using namespace std;

class loc { int longitude, latitude; public: loc() {} loc(int lg, int lt) { longitude = lg; latitude = lt; } void show() { cout << longitude << " "; cout << latitude << "\n"; } loc operator=(loc op2); friend loc operator++(loc &op); friend loc operator--(loc &op); }; // Overload assignment for loc. loc loc::operator=(loc op2) { longitude = op2.longitude; latitude = op2.latitude; return *this; // i.e., return object that generated call } // Now a friend; use a reference parameter. loc operator++(loc &op) { op.longitude++; op.latitude++; return op; } // Make op-- a friend; use reference. loc operator--(loc &op) { op.longitude--; op.latitude--; return op; } int main() { loc ob1(10, 20), ob2; ob1.show(); ++ob1; ob1.show(); // displays 11 21 ob2 = ++ob1; ob2.show(); // displays 12 22 --ob2; ob2.show(); // displays 11 21 return 0; }

If we want to overload the postfix versions of the increment and decrement operators using a friend, simply specify a second, dummy integer parameter. For example, this shows the prototype for the friend, postfix version of the increment operator relative to loc. // friend, postfix version of ++ friend loc operator++(loc &op, int x); 1. What is meant by operator overloading? 2. Which operators can not be overloaded?

2.6. Overloading new and delete It is possible to overload new and delete. You might choose to do this if you want to use some special allocation method. For example, you may want allocation routines that automatically begin using a disk file as virtual memory when the heap has been exhausted. Whatever the reason, it is a very simple matter to overload these operators. The skeletons for the functions that overload new and delete are shown here: // Allocate an object. void *operator new(size_t size) { /* Perform allocation. Throw bad_alloc on failure. Constructor called automatically. */ return pointer_to_memory; } // Delete an object. void operator delete(void *p) { /* Free memory pointed to by p. Destructor called automatically. */ } The type size_t is a defined type capable of containing the largest single piece of memory that can be allocated. (size_t is essentially an unsigned integer.) The parameter size will contain the number of bytes needed to hold the object being allocated. This is the amount of memory that our version of new must allocate.

The overloaded new function must return a pointer to the memory that it allocates, or throw a bad_alloc exception if an allocation error occurs. Beyond these constraints, the overloaded new function can do anything else you require. When you allocate an object using new (whether your own version or not), the object's constructor is automatically called. The delete function receives a pointer to the region of memory to be freed. It then releases the previously allocated memory back to the system. When an object is deleted, its destructor function is automatically called. Example #include <iostream> #include <cstdlib> #include <new> using namespace std; class loc { int longitude, latitude; public: loc() {} loc(int lg, int lt) { longitude = lg; latitude = lt; } void show() { cout << longitude << " "; cout << latitude << "\n"; } void *operator new(size_t size); void operator delete(void *p); }; // new overloaded relative to loc. void *loc::operator new(size_t size) { void *p; cout << "In overloaded new.\n"; p = malloc(size); if(!p) { bad_alloc ba; throw ba; } return p; } // delete overloaded relative to loc. void loc::operator delete(void *p) { cout << "In overloaded delete.\n"; free(p); }

int main() { loc *p1, *p2; try { p1 = new loc (10, 20); } catch (bad_alloc xa) { cout << "Allocation error for p1.\n"; return 1; } try { p2 = new loc (-10, -20); } catch (bad_alloc xa) { cout << "Allocation error for p2.\n"; return 1;; } p1->show(); p2->show(); delete p1; delete p2; return 0; } Output from this program is. In overloaded new. In overloaded new. 10 20 -10 -20 In overloaded delete. In overloaded delete.

SUMMARY: Programming a computer includes: Learning the syntax of a programming language Resolving logical errors

Programming languages provide methods for input and output of variable values. Procedural programs consist of a series of steps or procedures that take place one after the other. Object-oriented programming adds several new programming concepts including objects, classes, inheritance, and polymorphism. You write a C++ program by typing source code into an editor and compiling the program.C++ modules are called functions, and each function contains a header and a body.C++ variables must be given a type and a name.Comments are nonexecuting program statements

A preprocessor directive tells the compiler to do something before compiling the program.Use cout and cin to display and read values.When you create a data structure or class, you create your own C++ data type

Keywords: Ada Assembly language C++ Classes Concurrency Data abstraction Data encapsulation Data hiding Data members Dynamic binding Early binding Eiffel Flowcharts Function overloading Functions Garbage collection Global data Hierarchical classification Inheritance Java Late binding Local data Machine language Member functions Message passing

Methods Modular programming Multiple Inheritance Object Libraries Object Pascal LAB CYCLE

1. Write a C++ program to generate a pyramid using a set of integer numbers. 2. Write a C++ program to solve a Quadratic equation. 3. Write a C++ program to generate a Fibonacci series of N numbers. 4. Write a function in C++ program to find the sum of the following series. a) sum=1+3+5++n b) sum =x+x 2 /2!+x 4 /4!....+x n /n! 5. Write a C++ program to read a line and find out the number of vowels(a,e,I,o,u). 6. Write a C++ program to find the largest and smallest number in the given set of N numbers. 7. Write a program to read any four characters and print out all the possible combinations. 8. Write a program in C++ to read a set of characters using a pointer and to print in the reverse order. 9. Write an object oriented program in C++ to read an integer number and find out the sum of all the digits until it comes to a single digit. 10. Write an oop in C++ that prints whether a given number is prime or not. 11. Write an OOP in C++ to read a number n and print it digit by digit in words using inline member function. 12. Write an OOP in C++ to read two dimensional array; find the sum of the elements row-wise and column-wise separately, and display the sums using new and delete operators. 13. Develop an OOP in C++ to create a data base of the following items of the derived class. Name of the patient

Sex Age Ward number Bed number Nature of illness Date of admission Design a base class consisting of the data members, viz, name of the patient,sex, and age and another base class consisting of ward number,bed number and nature of the illness. The derived class consists of the data member, date of admission. Develop the program for the following facilities. build a master table list a table insert a new entry delete old entry search a record that is to be printed

14. Write a function overloading program to read a set of coordinates of a rectrangle. 15. Write a program in C++ to perform the following using operator overloading: a) Area of a circle b) Area of a rectangle c) Area of triangle 16.Write an OOP in C++ using polymorphic technique that prints either the number and its square or the number and its cube from 0 to 100. 17.Write a program in C++ to perform the following using the function template concepts: i) to read a set of integers ii) to read a set of floating point numbers iii) to read a set of double numbers individually. Find out the average of the non-negative integers and also calculate the deviation of the numbers.

18.Write a program in C++ to read students record such as name,sex,roll number, height, and weight from the specified file and to display in a sorted order.(name is the key sorting) 19. Write a program in C++ to merge two files into one file heading. 20. Write an OOP in C++ to add, subtract of any two given complex numbers using friend function.

PART-A (2 MARKS) 1. WRITE ANY FOUR FEATURES OF OOPS. 2. WHAT ARE THE BASIC CONCEPTS OF OOS? 3. DEFINE OBJECTS. 4. DEFINE CLASS. 5. GIVE ANY FOUR ADVANTAGES OF OOPS. 6. GIVE ANY FOUR APPLICATIONS OF OOPS. 7. GIVE ANY FOUR APPLICATIONS OF C++. 8. DEFINE TOKENS. 9. WHAT IS KEYWORD? 10. RULES FOR NAMING THE IDENTIFIERS IN C++. 11. WHAT IS A SCOPE RESOLUTION OPERATOR? 12. WHAT DO YOU MEAN BY ENUMERATED DATA TYPE? 13. WHAT ARE SYMBOLIC CONSTANTS? 14. WHAT DO YOU MEAN BY DYNAMIC INITIALIZATION OF VARIABLES? 15. WHAT ARE REFERENCE VARIABLE? 16. WHAT IS MEANT BY OPERATOR OVERLOADING? 17. DEFINE CONSTRUCTOR. 18. DEFINE DEFAULT CONSTRUCTOR. 19. DEFINE PARAMETERIZED CONSTRUCTOR. 20. DEFINE DEFAULT ARGUMENT CONSTRUCTOR. 21. WHAT IS THE AMBIGUITY BETWEEN DEFAULT CONSTRUCTOR AND DEFAULT ARGUMENT CONSTRUCTOR? 22. DEFINE COPY CONSTRUCTOR.

23. DEFINE DYNAMIC CONSTRUCTOR. 24. DEFINE CONST OBJECT. 25. DEFINE DESTRUCTOR. 26. DEFINE MULTIPLE CONSTRUCTORS. 27. WRITE SOME SPECIAL CHARACTERISTICS OF CONSTRUCTOR 28. WHICH OPERATORS CAN NOT BE OVERLOADED? 29. WRITE ANY FOUR FEATURES OF OOPS. 30. WHAT ARE THE BASIC CONCEPTS OF OOS? 31. DEFINE OBJECTS. 32. DEFINE CLASS. 33. GIVE ANY FOUR ADVANTAGES OF OOPS. 34. GIVE ANY FOUR APPLICATIONS OF OOPS. 35. GIVE ANY FOUR APPLICATIONS OF C++. 36. DEFINE TOKENS. 37. WHAT IS KEYWORD? 38. RULES FOR NAMING THE IDENTIFIERS IN C++. 39. WHAT IS A SCOPE RESOLUTION OPERATOR? 40. WHAT DO YOU MEAN BY ENUMERATED DATA TYPE? 41. WHAT ARE SYMBOLIC CONSTANTS? 42. WHAT DO YOU MEAN BY DYNAMIC INITIALIZATION OF VARIABLES? 43. WHAT ARE REFERENCE VARIABLE?

PART-B (12 MARKS) 1. EXPLAIN WITH THE BASIC CONCEPTS OF OBJECT ORIENTED

PROGRAMMING. (a) EXPLAIN THE ELEMENTS OF OBJECT ORIENTED PROGRAMMING. (8) (b) WHAT ARE THE DIFFERENCE BETWEEN REFERENCE VARIABLES AND NORMAL VARIABLES? WHY CANNOT A 2. CAN CONSTANT VALUE BE INITIALIZED TO VARIABLES OF REFERENCE TYPE? (8) 3. EXPLAIN ABOUT CALL-BY-REFERENCE AND POINTER TYPES WITH PROGRAM.

(a) DESCRIBE THE ADVANTAGES OF OOP. (8) (b) WHAT ARE THE DIFFERENCE BETWEEN POINTERS TO CONSTANTS AND CONSTANT TO POINTERS? (8) (a) DESCRIBE THE APPLICATIONS OF OOP TECHNOLOGY. (8) (b) WHAT IS FUNCTION INVOCATION? EXPLAIN BRIEFLY WITH PROGRAM. (8) 4. EXPLAIN ABOUT DATA HANDLING AND MEMBER FUNCTION. EXPLAIN COPY CONSTRUCTOR AND DESTRUCTOR WITH SUITABLE C++ CODING 5. EXPLAIN OPERATOR OVERLOADING WITH AN EXAMPLE. 6. HOW DO YOU OVERLOAD THE OPERATORS NEW AND DELETE? GIVE A SAMPLE PROGRAM TO IMPLEMENT BOTH. 7. DISCUSS ABOUT THE CONSTRUCTOR OVERLOADING IN DETAIL. GIVE AN EXAMPLE TO IMPLEMENT IT. 8. DISCUSS ABOUT VARIOUS TYPES OF CONSTRUCTORS IN DETAIL. GIVE SOME EXAMPLES. 9. HOW DO YOU OVERLOAD THE OPERATORS NEW AND DELETE? GIVE A SAMPLE PROGRAM TO IMPLEMENT BOTH. 10. EXPLAIN WITH THE BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING. (c) EXPLAIN THE ELEMENTS OF OBJECT ORIENTED PROGRAMMING. (8) (d) WHAT ARE THE DIFFERENCE BETWEEN REFERENCE VARIABLES AND NORMAL VARIABLES? WHY CANNOT A (e) CAN CONSTANT VALUE BE INITIALIZED TO VARIABLES OF REFERENCE TYPE? (8) 11. EXPLAIN ABOUT CALL-BY-REFERENCE AND POINTER TYPES WITH PROGRAM. (c) DESCRIBE THE ADVANTAGES OF OOP. (8) (d) WHAT ARE THE DIFFERENCE BETWEEN POINTERS TO CONSTANTS AND CONSTANT TO POINTERS? (8) (c) DESCRIBE THE APPLICATIONS OF OOP TECHNOLOGY. (8) (d) WHAT IS FUNCTION INVOCATION? EXPLAIN BRIEFLY WITH PROGRAM. (8)

You might also like