1 of 136

OBJECT ORIENTED PROGRAMMING IN C++ �[UNIT-I]

U4.1

2 of 136

Learning Objectives

  • Principles of Object-Oriented Programming Approach
  • Object
  • Classes
  • Data Abstraction
  • Data Encapsulation
  • Inheritance
  • Polymorphism
  • Dynamic Binding
  • Message Passing
  • POP vs. OOPS
  • Examples of Basic C++ Programs

U4.2

3 of 136

PROGRAMMING PARADIGMS

  • A programming paradigm is a general approach to programming or to the solution of problems using a programming language. Thus programming languages that share similar characteristics are clustered together in the same paradigm.

OBJECT-ORIENTED PROGRAMMING

OBJECT-BASED PROGRAMMING

PROCEDURAL PROGRAMMING

ASSEMBLY LANGUAGE

MACHINE LANGUAGE

U4.3

4 of 136

PROGRAMMING PARADIGMS

 

  • The major paradigms are:
  • Procedural: Subroutines and global data items; eg: ALGO, FORTRAN, BASIC and COBOL
  • Structured : Emphasis on algorithms rather than data; eg: PASCAL and C
  • Object-based: Support object creation; eg: Modula-2
  • Object-oriented: Classes and objects; eg: C++,Smalltalk, Eiffel and Java
  • Logical : Goals, often expressed in predicate calculus
  • Rule-based : if-then-else rules
  • Data base query languages: SQL
  • Visual: VB,VB C++
  • Scripts
  • Programming by Demonstration

U4.4

5 of 136

Procedural Programming��

  • Divide a program into functions / subroutines/ procedures, also called Procedure Oriented Programming (POP).
  • Programs organized in the form of procedures and all data items are global. Hence data is not protected.
  • Program controls are through jumps (goto) and call to the subroutine.
  • As programs increase in complexity, management becomes difficult.
  • Subroutines are abstracted to avoid repetitions.
  • Hierarchical in nature.

U4.5

6 of 136

Procedural Programming

Advantages:

  • Suitable for Medium sized applications.
  • Minimize Duplication of data.
  • Reduce errors.
  • Saves time, money & space.

U4.6

7 of 136

Procedural Programming

  • Disadvantages:
  • Since global data is accessible to all functions so the data can be easily corrupted.
  • Since many functions access the same data, the way the data is stored becomes critical. The arrangement of the data can not be changed without modifying all the functions that access it.
  • Like other traditional languages, Extensibility ( Creating new data type) is not possible.
  • Difficult to maintain/enhance the program code.
  • Does not model real world very well.

U4.7

8 of 136

Languages that support programming with objects are said to be object based programming languages.

  • Data encapsulation
  • Data hiding
  • Access mechanisms
  • Operator overloading

They do not support inheritance and dynamic binding.

Ex-89’Ada, Modula-2

Object Oriented Programming

Objects based features+ inheritance+ dynamic binding

Object Based Programming

U4.8

9 of 136

Object Oriented Programming

  • Object = Data + Methods.
  • Problem is divided into Objects ( data structure with data fields, methods and their interaction) rather than Functions.
  • It ties data more closely to the functions and does not allow it to flow freely around the system [Data Abstraction].
  • Use Bottom-up program technique for program design.
  • Objects communicate by sending message to one another.
  • New data & functions can be easily added whenever necessary. [Inheritance].

U4.9

10 of 136

Object Oriented Programming

  • Advantages:
  • Increased programming productivity.
  • Reusable Code.
  • Decreased maintenance code.
  • Greater speed.
  • Lesser Complexities.
  • Abstraction makes it possible to change the data structure of an object, without affecting the operation of the program.

U4.10

11 of 136

STRUCTURED VS. OBJECT-ORIENTED

  • Program and data two basic elements of computation. Data can exist without a program, but a program has no relevance without data.
  • Conventional high level languages stress on algorithms used to solve a problem. Here, data are defined as global and accessible to all parts of a program without any restriction, hence reduced data security and integrity.
  • Object-Oriented programming emphasizes on data rather than the algorithm. Here, data is encapsulated with the associated functions into an object.
  • OOP is centered around the concepts of objects, encapsulation, abstract data types, inheritance, polymorphism, message based communication, etc.

U4.11

12 of 136

Object-Based versus Object-Oriented

  • Object-Based Programming usually refers to objects without inheritance and hence without polymorphism, as in '83 Ada and Modula-2. These languages support abstract data types (Adts) and not classes, which provide inheritance and polymorphism.
  • object-oriented = data abstractions + object types + type inheritance.

OR�Object-Oriented = Classes and Objects + Inheritance + Communication with messages�The main difference between object oriented and object based languages is object based languages doesn't support Inheritance where as object oriented supports.

U4.12

13 of 136

FEATURES OF OOP

U4.13

14 of 136

HISTORY OF C++

U4.14

15 of 136

C versus C++

  • C follows structured programming while C++ is object-oriented.
  • C does not provide data abstraction, hence data is not secure. C++ provides data abstraction.
  • C is mainly function driven, while C++ is object-driven.
  • C++ supports function overloading, while C does not.
  • C does not use namespaces to avoid name collisions while C++ does.
  • Standard I/O differs in C and C++
  • C++ allows use of reference variables while C does not.
  • C++ supports exception handling while C does not.
  • C++ is a superset of C, earlier called C with classes.
  • Classes and inheritance are a major addition to C++.
  • C programs can be compiled in C++ compiler.

U4.15

16 of 136

Structure of C++ Program

  • C programs use the file extension .C and C++ programs use the extension .CPP. A C++ compiler uses the file extension to determine what type of program it is compiling.

Using C++ hello.cpp

//hello.cpp: printing Hello World message

#include <iostream.h>

void main(){

cout<< “Hello world”;

}

U4.16

17 of 136

Structure of C++ Program

/* greeting.cpp greets its user. * * Input: The name of the user * Output:

A personalized greeting */

#include <iostream> //preprocessor directive for iostream header file

#include <string> //preprocessor directives

int main()//main function declaration

{ //block scope

cout << "Please enter your first name: ";

string firstName;

cin >> firstName;

cout << "\nWelcome to the world of C++, "

<< firstName << "!\n"; return 0;}

U4.17

18 of 136

All the elements of the standard C++ library are declared within what is called a namespace, the namespace with the name std. So in order to access its functionality we declare with this expression that we will be using these entities. This line is very frequent in C++ programs that use the standard library, and in fact it will be included in most of the source codes

U4.18

19 of 136

ANSI/ISO Standard C++

  • International Standard for the C++ programming language is ANSI/ISO/IEC 14882:1998 which first became a standard in 1998.
  • It includes: Standard library: Header file names no longer maintain the .h extension typical of the C language and of pre-standard C++ compilers
  • Header files that come from the C language now have to be preceded by a c character in order to distinguish them from the new C++ exclusive header files that have the same name. For example stdio.h becomes cstdio
  • All classes and functions defined in standard libraries are under the std namespace instead of being global.
  • Standard Template library: Wide range of collection classes
  • Exception handling
  • Namespaces

U4.19

20 of 136

Comments

In C++, there are two different comment delimiters:

    • the comment pair (/*, */),
    • the double slash (//).

The comment pair is identical to the one used in C:

    • The sequence /* indicates the beginning of a comment.
    • The compiler treats all text between a /* and the following */ as a comment.
    • A comment pair can be multiple lines long and can be placed wherever a tab, space, or newline is permitted.
    • Comment pairs do not nest.
    • // serves to delimit a single line comment. Everything on the program line to the right of the delimiter is treated as a comment and ignored by the compiler.

U4.20

21 of 136

Variables

a variable is a named location in memory that is used to hold a value that may be modified by the program. All variables must be declared before they can be used. The general form of a declaration is

type variable_list;

Here, type must be a valid data type plus any modifiers, and variable_list may consist of

one or more identifier names separated by commas. Here are some declarations:

int i,j,l;

short int si;

unsigned int ui;

double balance, profit, loss;

U4.21

22 of 136

Operating with Variables

// initialization of variables

#include <iostream>

using namespace std;

int main ()

{

int a=5; // initial value = 5

int b=2; // initial value = 2

int result; // initial value undetermined

a = a + 3;

result = a - b;

cout << result;

return 0;

}

o/p=6

U4.22

23 of 136

const

  • Variables of type const may not be changed by your program. (A const variable can be given an initial value, however.) The compiler is free to place variables of this type into read-only memory (ROM). For example,
  • const int A=10;
  • creates an integer variable called a with an initial value of 10 that your program may not modify.
  • They are treated just like regular variables except that their values cannot be modified after their definition.

U4.23

24 of 136

Stream Based I/O

C++’s feature for handling I/O operations are called streams

Streams are abstractions that refer to data flow.

Stream in C++ are classified into

    • Output Streams
    • Input Streams
  • Output Stream performs write operations on output devices
  • Syntax is cout<< variable
  • More than one item can be displayed using single output stream object called cascaded output operations

cout<< “Age = “<< age;

U4.24

25 of 136

Input Streams

  • Perform read operation with input devices
  • Performed using cin object
  • extracts data from a stream and copies the extracted information to variables
  • skip all white space characters that precede the values to be extracted
  • Syntax: int age; cin >>age;
  • Input of more than one item can also be performed using the cin input stream object called cascaded input operations
      • cin >> name>> age;
  • Object cin, must be associated with at least one argument.

U4.25

26 of 136

Enumerated types

  • An enumeration is a data type in which labels for all possible values of the type can be listed
  • The type declaration consists of the keyword enum followed by the name of the new type and a block of code in which labels for all values of the type are listed. Syntax:

enum NewTypeName {value1, value2, … , valueN};

  • The value labels in an enumeration are called enumeration constants. Enumeration constants must be valid C++ identifiers; they are not string or char literals
  • Enumeration constants are stored in memory as integers; by default, the first is assigned the value 0, the second 1, etc.
  • Thus the order of the listing determines the relative magnitude of enumeration constant values; the first is less than the second, which is less than the third, and so forth

U4.26

27 of 136

Specifying different values in enumerations

  • By default, the first enumeration constant has the value 0, the second 1, the third 2, etc.
  • The default behavior can be overridden by assigning explicit values to one or more of the constants
  • For Ex: The following enumeration uses explicit assignment to specify values for the symbols used in the Roman numeral system:

enum RomanNum { I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000};

U4.27

28 of 136

Example 2 (enum)

  • The following enumeration type creates constants that stand for the months of the year:

enum MonthType {JAN=1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};

  • Only the first constant’s value is specified; since it is 1, the second is 2, the third is 3, and so on until the last (DEC) with the value 12

U4.28

29 of 136

Using enumerated types

  • Enumerations only create new data types; to actually store and use values of the new types, you must declare variables
  • Variables of each enum type can hold only those values specified by the enumeration
  • For example, with the MonthType enumeration, you could declare variables and assign them values like the following:

MonthType thisMonth = APR;

MonthType nextMonth = MAY;

MonthType birthMonth = nextMonth;

U4.29

30 of 136

Operations on enumerations

  • Since enumerations are not built-in data types, only some of the most common operations can be performed using variables of these types
  • The allowable operations include:
    • logical comparison using the relational operators (<, >, <=, >=, ==, !=)
    • simple arithmetic (but not arithmetic/assignment operations like ++ or --)
    • enumerations can be parameters to, and/or return values from, functions
    • enumerations can be used as switch expressions and/or case labels in switches – example on next slide

U4.30

31 of 136

MonthType thisMonth;

switch ( thisMonth ) // using enum type switch expression

{

case JAN :

case FEB :

case MAR : cout << “Winter quarter” ;

break ;

case APR :

case MAY :

case JUN : cout << “Spring quarter” ;

break ;

case JUL :

case AUG :

case SEP : cout << “Summer quarter” ;

break ;

case OCT :

case NOV :

case DEC : cout << “Fall quarter” ;

}

U4.31

32 of 136

Incrementing enum variables using type cast mechanism

  • The operators ++ and -- are not available for use with enum-type variables, as previously noted
  • However, enum-type variables can appear in mixed-type expressions with, for example, integers
  • This provides a mechanism for increment/decrement of enumeration type variables

U4.32

33 of 136

Using enum type Control Variable with for Loop

MonthType month ;

for (month = JAN ; month <= DEC ; month = MonthType (month + 1 ) )

{ // uses type cast to increment

.

.

.

}

U4.33

34 of 136

Simple arithmetic with enumeration constants

  • Previously, we defined an enumeration of the symbols used in the Roman numeral system
  • We will use this enumeration to illustrate arithmetic with enums, and see another example of type casting.
  • Note: The insertion (<<) and extraction (>>) operators are not defined for enum-type variables
  • To perform input or output operations on user-defined types, you must provide your own functions.

U4.34

35 of 136

Example

#include <iostream.h>

#include <stdlib.h>

enum RomanNum {I=1, V=5, X=10, L=50, C=100, M=1000};

int main()

{

cout << "Welcome to the world of Roman numerals!" << endl;

int num = (int)(M + C + L + X + V + I);

cout << "MCLXVI=" << num << endl;

num = (int)((L-X) + (V-I));

cout << "XLIV=" << num << endl;

system("PAUSE");

return 0;

}

U4.35

36 of 136

Arrays Hold Multiple values

  • Unlike regular variables, arrays can hold multiple values.

U4.36

37 of 136

//This program asks the user for the number of hours worked

// by 6 employees. It uses a 6-element int array to store the

// values.

#include <iostream.h>

void main(void)

{

short hours[6];

cout << "Enter the hours worked by six employees: ";

cin >> hours[0];

cin >> hours[1];

cin >> hours[2];

cin >> hours[3];

U4.37

38 of 136

Program continues

cin >> hours[4];

cin >> hours[5];

cout << "The hours you entered are:";

cout << " " << hours[0];

cout << " " << hours[1];

cout << " " << hours[2];

cout << " " << hours[3];

cout << " " << hours[4];

cout << " " << hours[5] << endl;

}

U4.38

39 of 136

Array Initialization

  • int A[5] = {2, 4, 8, 16, 32};
      • Static or automatic
  • int B[20] = {2, 4, 8, 16, 32};
      • Unspecified elements are guaranteed to be zero
  • int C[4] = {2, 4, 8, 16, 32};
      • Error — compiler detects too many initial values

U4.39

40 of 136

Initializing Allocated Memory

  • You can initialize allocated memory to some known value by putting an initializer after the type name in the new statement. Here is the general form of new when an initialization is included:
  • p_var = new var_type (initializer);

U4.40

41 of 136

Allocating Arrays

You can allocate arrays using new by using this general form:

p_var = new array_type [size];

Here, size specifies the number of elements in the array.To free an array, use this form of delete:

delete [ ] p_var;

Here, the [ ] informs delete that an array is being released.

For example, the next program allocates a 10-element integer array.

U4.41

42 of 136

No Bounds Checking

There are no checks in C++ that an array subscript is in range

An invalid array subscript can cause program to overwrite other memory

Example:

const int ISIZE = 3;

int i = 4;

int num[ISIZE];

num[i] = 25;

U4.42

43 of 136

// This program uses an array of ten characters to store the

// first ten letters of the alphabet. The ASCII codes of the

// characters are displayed.

#include <iostream.h>

void main()

{

char letters[10] = {'A', 'B', 'C', 'D', 'E',

'F', 'G', 'H', 'I', 'J'};

cout << "Character" << "\t" << "ASCII Code\n";

cout << "--------" << "\t" << "----------\n";

for (int count = 0; count < 10; count++)

{

cout << letters[count] << "\t\t";

cout << int(letters[count]) << endl;

}

}

U4.43

44 of 136

// Precondition: n is a positive integer

// Postcondition: computes and prints out the first n

// elements of the Fibonacci sequence

void fibonacci(int n){

int *x = new int [n]; // creation of a dynamic array

x[0]=1; x[1]=1;

for (int i=2;i<n;i++)

x[i]=x[i-1]+x[i-2];

cout<<"The Fibonacci sequence of "<<n<<" values are:\n";

for (int i=0;i<n;i++)

cout<<"x["<<i<<"]="<<x[i]<<endl; }

U4.44

45 of 136

//read values and print them in reverse

#include <iomanip.h>

void main()

{

int x[5], index;

cout << “Please enter five integer values: “;

for( index=0; index<5; index++) cin >> x[index];

cout << “The values in reverse order are: “;

for (index=4; index>=0; index--)

cout << setw(3) << x[index];

cout << endl;

}

U4.45

46 of 136

Creating Multidimensional Arrays

int[][] matrix = new int[10][10];

or

int matrix[][] = new int[10][10];

matrix[0][0] = 3;

for (int i=0; i<matrix.length; i++)

for (int j=0; j<matrix[i].length; j++)

{

matrix[i][j] = (int)(Math.random()*1000);

}

U4.46

47 of 136

Arrays Example

#include <iostream> #include <new>

using namespace std;

int main()

{ int *p, i;

try {

p = new int [10]; // allocate 10 integer array

} catch (bad_alloc xa) {

cout << "Allocation Failure\n";

return 1; }

for(i=0; i<10; i++ )

p[i] = i;

for(i=0; i<10; i++)

cout << p[i] << " ";

delete [] p; // release the array

return 0;}

U4.47

48 of 136

Introduction to Pointers

  • When we declare a variable some memory is allocated for it. Thus, we have two properties for any variable : its address and its data value. The address of the variable can be accessed through the referencing operator “&”.
  • A pointer variable is one that stores an address. Ex: int* p; //This means that p stores the address of a variable of type int.
  • Q: Why is it important to declare the type of the variable that a pointer points to? Aren’t all addresses of the same length?
  • A: All addresses are of the same length, however when we perform an operation of the type “p++” where “p” is a pointer variable, for this operation to make sense the compiler needs to know the data type of the variable “p” points to. If “p” is a character pointer then “p++” will increment “p” by one byte (typically), if “p” were an integer pointer its value on “p++” would be incremented by 2 bytes (typically).

U4.48

49 of 136

Pointers and Arrays

  • The concept of array is very similar to the concept of pointer. The identifier of an array is actually a pointer that holds the address of the first element of the array.
  • Therefore if you have two declarations as follows:
    • “int a[10];” “int* p;” then the assignment “p = a;” is perfectly valid
    • Also “*(a+4)” and “a[4]” are equivalent as are “*(p+4)” and “p[4]” .
    • The only difference between the two is that we can change the value of “p” to any integer variable address whereas “a” will always point to the integer array of length 10 defined.

U4.49

50 of 136

Character Pointers, Arrays and Strings

  • What is a String?
    • A string is a character array that is ‘\0’ terminated.
    • E.g. “Hello”
  • What is a Character array?
    • It is an array of characters, not necessarily ‘\0’ terminated
    • E.g. char test[4] = {‘a’, ‘b’, ‘c’, ‘d’}; <this char array is not zero terminated>
  • What is a character pointer?
    • It is a pointer to the address of a character variable.
    • E.g. char* a; <this pointer is not initialized>

U4.50

51 of 136

Character Pointers, Arrays and Strings

  • How do we initialize a Character pointer?
    • Initialize it to NULL. char* a = NULL;
    • Let it point to a character array.
      • char* a; char b[100]; a = b;
    • Initialize to a character string.
      • char* a = “Hello”; a pointer to the memory location where ‘H’ is stored. Here “a” can be viewed as a character array of size 6, the only difference being that a can be reassigned another memory location.

U4.51

52 of 136

Examples

  • char* a = “Hello”;
    • a -> gives address of ‘H’
    • *a -> gives ‘H’
    • a[0] -> gives ‘H’
    • a++ -> gives address of ‘e’
    • *a++ -> gives ‘e’
    • a = &b; where b is another char variable is perfectly LEGAL. However “char a[100];” “a =&b;” where b is another char variable is ILLEGAL.

U4.52

53 of 136

Remember

  • Pointer is a datatype that stores addresses.
  • Values stored in a pointer are accessed through the dereferencing operator “*”
  • Address of a memory location of a variable can be accessed through the reference operator &.
  • Concept of array is similar to the concept of pointer.
  • Identifier of an array is actually a pointer that holds the address of first element of an array.
  • Hence: int a[10]; int*p; p=a;

U4.53

54 of 136

Void Pointers

  • Pointers variables declared as void, hence can accept data from any type of pointer.
  • Ex: void*gp;

int *ip;

  • ip= (int*) gp;

U4.54

55 of 136

Constant Pointers

  • Pointers for constants used in programs.
  • char *const ptr={“GOOD”};
  • //constant pointer with value GOOD
  • int const*ptr1=&m;
  • Pointer to a constant that accepts address of m variable. Contents of such pointers cannot be changed.

U4.55

56 of 136

Name and Address of an Array

  • Name of an array in C++ is the starting address for that array.
  • Ex: char town[]=“Beijing”;
  • Pointer to the first character of the string town is passed. Characters forming the string are read and displayed from this point onwards until the terminating null character, ‘\0’ is reached.

U4.56

57 of 136

CLASSES IN C++

U4.57

58 of 136

STRUCTURE OF C++ PROGRAM

INCLUDE FILES

CLASS DECLARATION

MEMBER FUNCTION DEFINITIONS

[to separate abstract specifications of the interface (class definition) from the implementation details (member function definition)]

MAIN FUNCTION PROGRAM

U4.58

59 of 136

CLASS

  • A class is a group of objects that share common properties & behavior/ relationships.
  • In fact, objects are the variables of the type class.
  • After creating class, one can create any no. of related objects with that class.
  • Classes are user defined data types and behaves like the built-in types of a programming language.

U4.59

60 of 136

// myclass1.cpp

#include <iostream.h>

class myclass1// class starts the declaration of a new class

{

private: //Data members are usually private

int num;

public: // Member functions are public in nature.

void getdata() // to enter the value

{

cout<<“Enter an integer:”;// cout keyword to display information

cin>>num; // cin is the keyword to enter data

}

MYCLASS1.CPP

U4.60

61 of 136

void dispdata() // to display the value

{

cout<<“Num=“ <<num<<endl;

}

}; // indicates the end of class command.

void main()

{

myclass1 a1, b1; / /a1 & b1 are objects of class myclass1.

a1.getdata();

b1.getdata();

a1.dispdata();

b1.dispdata();

}

MYCLASS1.CPP

U4.61

62 of 136

A constructor is a special function that is a member of a class and has the same name as that class. For example,

// This creates the class stack.

class stack {

int stck[SIZE]; int tos;

public:

stack(); // constructor

void push(int i);int pop();};

Notice that the constructor stack( ) has no return type specified. In C++, constructors cannot return values and, thus, have no return type.

The stack( ) constructor is coded like this:

// stack's constructor

stack::stack()

{tos = 0;cout << "Stack Initialized\n";

}

Constructors

U4.62

63 of 136

  • Constructor is automatically named when an object is created. A constructor is named whenever an object is defined or dynamically allocated using the "new" operator.
  • A constructor takes the same name as the class name.
  • The programmer cannot declare a constructor as virtual or static, nor can the programmer declare a constructor as const.
  • No return type is specified for a constructor; not even void.
  • The constructor must be defined in the public. The constructor must be a public member.
  • Overloading of constructors is possible.
  • Each class can have only one default constructor.

Some important points about constructors:

Constructors

U4.63

64 of 136

The complement of the constructor is the destructor.

There are many reasons why a destructor may be needed. For example, an object may need to deallocate memory that it had previously allocated or it may need to close a file that it had opened.

In C++, it is the destructor that handles deactivation events.

The destructor has the same name as the constructor, but it is preceded by a ~

For example, here is the stack class and its constructor

and destructor.

Destructors

U4.64

65 of 136

Some important points about destructors:�Destructors take the same name as the class name.

  • Like the constructor, the destructor must also be defined in the public. The destructor must be a public member.
  • The Destructor does not take any argument which means that destructors cannot be overloaded.
  • No return type is specified for destructors. 
  • The use of destructors is especially suitable when an object assigns dynamic memory during its lifetime and at the moment of being destroyed we want to release the memory that the object was allocated.
  • A class cannot have more than on destructor.
  • Destructor can be virtual but constructor can not be.

Destructors

U4.65

66 of 136

This creates the class stack.

class stack {

int stck[SIZE];

int tos;

public:

stack(); // constructor

~stack(); // destructor

void push(int i);

int pop();

};

// stack's constructor

stack::stack()

{

tos = 0;

cout << "Stack Initialized\n";

}

// stack's destructor

stack::~stack()

{

cout << "Stack Destroyed\n";

}

Notice that, like constructors, destructors do not have return values.

U4.66

67 of 136

  • Like any other function, a constructor can also be overloaded with more than one function that have the same name but different types or number of parameters.
  • Remember that for overloaded functions the compiler will call the one whose parameters match the arguments used in the function call.
  • If we declare a new object and we want to use its default constructor (the one without parameters), we do not include parentheses ():

CRectangle rectb; // right

CRectangle rectb(); // wrong!

Overloaded Constructors

U4.67

68 of 136

  • C++ allows a function to assign a parameter a default value when no argument corresponding to that parameter is specified in a call to that function. The default value is specified in a manner syntactically similar to a variable initialization.
  • For example, this declares myfunc( ) as taking one double argument with a default value of 0.0:

void myfunc(double d = 0.0)

{// ...

}

Now, myfunc( ) can be called one of two ways, as the following examples show:

myfunc(198.234); // pass an explicit value

myfunc(); // let function use default

Default Function Arguments

U4.68

69 of 136

Class Example

// example: class constructor

#include <iostream>

using namespace std;

class CRectangle

{

int width, height;

public:

CRectangle (int,int);

int area ()

{

return (width*height);

}

};

CRectangle::CRectangle (int a, int b)

{

width = a;

height = b;

}

int main ()

{

CRectangle rect (3,4);

CRectangle rectb (5,6);

cout << "rect area: " << rect.area() << endl;

cout << "rectb area: " << rectb.area() << endl;

return 0;

}

U4.69

70 of 136

Try Out Yourself?

1.Write a program to define a class student. Write function to take the information from user and display the information to user.

2.Write program for a library database using class and with the following data items:

Title of Book

Acc Number

Author

Publisher

Price

 

Write the class with both a constructor and a member function to initialize the data members.

U4.70

71 of 136

Try out Yourself?

Create a class employee which have name, age and address of the employee. Include functions getdata() and showdata(). Showdata takes the input from the user and display on the monitor in a tabular format and use inline with getdata().

Name:

Age:

Address:.

U4.71

72 of 136

Class Diagram of Employee class

Class: employee

Data:

Name

Dept

Desig

Basic

Functions:

Setbp( )

Totsal( )

Deductions( )

U4.72

73 of 136

ABSTRACTION

  • It refers to the act of representing essential features without including the background details or explanations.
  • Explanation (Driving a Car):

  • (Need to Know): Gear handling, Steering handling, Use of Clutch, Brakes, Accelerator etc.
  • (Not Necessary to know): Internal details like wiring, Engine details & functions.

U4.73

74 of 136

ENCAPSULATION

  • The wrapping up of data & functions (that operate on the data) into a single unit (called class) is known as ENCAPSULATION.
  • Encapsulation is a way to implement data abstraction.
  • Only Relevant details are exposed and rest are made hidden. [Data Security]
  • Example: Departmental data, ATM cash counter, Weighing Machine etc.

U4.74

75 of 136

MODULARITY

  • The act of partitioning a program into individual components i.e. into a set of cohesive and loosely couple modules.

Example: A Music system comprises of speaker, cassette player, CD player, tuner etc. Though these are different entities in themselves, they work in unity towards achieving one goal i.e. music.

U4.75

76 of 136

Contd.

Advantages:

  • It reduces the complexity of a system to a greater extent.
  • It creates a number of well defined document boundaries within the program.
  • Makes data secure.
  • Faster speed.
  • Debugging easier.

U4.76

77 of 136

INHERITANCE

  • Inheritance is the capability of one class of things to inherent properties from other class.
  • Supports the concept of Hierarchical classification.
  • Ensures the closeness with real world models.
  • Provides Multiple Access Specifiers across the modules (Public, Private & Protected)
  • Supports Reusability that allows the addition of extra features to an existing class without modifying it.

U4.77

78 of 136

U4.78

79 of 136

U4.79

80 of 136

Public, Protected, Private Inheritance

class A {

public:

int i;

protected:

int j;

private:

int k;

};

Class B : public A { // ...

};

Class C : protected A {// ...

};

Class D : private A {// ...

};

  • Class A declares 3 variables
    • i is public to all users of class A
    • j is protected. only be used by methods in class A or its derived classes
    • k is private. It can only be used by methods in class A
  • Class B inherits publicly from A
    • i is again public to all users of class B, while j is again protected. It can be used by methods in class B or its derived classes
  • Class C uses protected inheritance from A
    • i is now protected in C, so the only users of class C that can access i are the methods of class C
    • j is again protected. It can be used by methods in class C or its derived classes
  • Class D uses private inheritance from A
    • i and j are private in D, so users of D cannot access them, only methods of D itself

U4.80

81 of 136

POLYMORPHISM / OVERLOADING

  • A Greek term suggest the ability to take more than one form.
  • Typically occurs when there is a hierarchy of classes related by inheritance.
  • Simply implies that call to a member function will cause a different object to be executed, depending on the type of object that invokes the function.
  • It is a property by which the same message can be sent to the objects of different class.

Example: Draw a shape (Box, Triangle, Circle etc.), Move ( Chess, Traffic, Army).

U4.81

82 of 136

Need???

  • It simplifies the programming interface.
  • It permits conventions to be established that can be reused in class after class.
  • Instead of inventing a new name for each new function you add to a program the same names can be reused.
  • The programming interface can be described as a set of abstract behaviors quite apart from the classes that implement them.

U4.82

83 of 136

U4.83

84 of 136

Compile time polymorphism

  • involves binding of functions based on the
    • number of arguments,
    • type of arguments
    • sequence of arguments.
  • This information is known to the compiler at compile time. So compiler selects the appropriate function for a particular call at compile time itself.
  • The various parameters are specified in the function declaration, and therefore the function can be bound to calls at compile time.
  • This form of association is called early binding. The term early binding implies that when the program is executed, the calls are already bound to the appropriate functions.

U4.84

85 of 136

Function overloading

#include <iostream>�using namespace std;�class arith {�public: void calc(int num1)�{cout<<"Square of a given number: " <<num1*num1 <<endl;}�   void calc(int num1, int num2 )�{cout<<"Product of two whole numbers: " <<num1*num2 <<endl;�}};

int main() //begin of main function�{�    arith a;�    a.calc(5);�    a.calc(6,7);}

U4.85

86 of 136

Runtime Polymorphism�

  • refers to an entity changing its form depending on circumstances.
  • A function is said to exhibit dynamic polymorphism when it exists in more than one form, and calls to its various forms are resolved dynamically when the program is executed.
  • The term late binding  refers to the resolution of the functions at run-time instead of compile time. This feature increases the flexibility of the program by allowing the appropriate method to be invoked, depending on the context.

U4.86

87 of 136

Virtual Member Function?

  • A virtual function allows derived classes to replace or redefine the implementation provided by the base class.
  • The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer.
  • This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.
  • We can say shortly that:
  • The virtual keyword indicates to the compiler that
    • it should choose the appropriate definition of a function not by the type of reference, but by the type of object that the reference refers to.

For this it uses concepts of dynamic binding.

U4.87

88 of 136

Dynamic binding

  • Means that the address of the code in a member function invocation is determined at the last possible moment based on the dynamic type of the object at run time.
  • Syntax:
  • prefix declaration with the virtual keyword
  • redefine a virtual member function in any derived class
  • this is called overriding
  • Example:

class A

{ public:� virtual void f() { cout << "Class A" << endl;} };

class B: public A {

public:� void f(int) { cout << "Class B" << endl; }};

U4.88

89 of 136

Contd…

  • overridden function must have same name and same parameter list
    • no need to use the virtual keyword again
    • return type can be different
  • if the parameter lists are different, they are considered different
    • in this case, it is not overridden, but hidden
    • hidden methods cannot be called

U4.89

90 of 136

Class, Objects and Memory Resources

  • When an object is created, memory is allocated only to its data members and not to member Function.

  • Member functions are created and stored in memory only once when a class specification is declared.

  • Member function are same for all objects.

  • Storage Space for data members which are declared as static is allocated only once during the class declarations.

U4.90

91 of 136

Constructors that Allocate Memory Dynamically�[Dynamic Constructors]

  • Constructors can be used to initialize member objects as well as to allocate memory. Memory allocation at run-time is also known as dynamic memory allocation.
  • C++ provides two dynamic allocation operators: new and delete. These operators are used to allocate and free memory at run time.
  • C++ also supports dynamic memory allocation functions, called malloc( ) and free( ). These are included for the sake of compatibility with C.
  • The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new.
  • Overloading of new and delete operator is possible

U4.91

92 of 136

  • delete is a keyword and the pointer variable is the pointer that points to the objects already created in the new operator.
  • We know that sizeof operator is used for computing the size of the object. Using memory management operator, the size of the object is automatically computed.
  • Null pointer is returned by the new operator when there is insufficient memory available for allocation.
  • new automatically allocates enough memory to hold an object of the specified type. You do not need to use the sizeof operator. Because the size is computed automatically, it eliminates any possibility for error in this regard.
  • new automatically returns a pointer of the specified type. You don't need to use an explicit type cast as you do when allocating memory by using malloc( ).

Dynamic Allocation Operators

U4.92

93 of 136

  • The general forms of new and delete are shown here:

p_var = new type;

delete p_var;

Here, p_var is a pointer variable that receives a pointer to memory that is large enough to hold an item of type type. Since the heap is finite, it can become exhausted. If there is insufficient available

memory to fill an allocation request, then new will fail and a bad_alloc exception will be generated. This exception is defined in the header <new>. Your program should handle this exception and take appropriate action if a failure occurs. If this exception is not handled by your program, then your program will be terminated.

Dynamic Allocation Operators

U4.93

94 of 136

The trouble is that not all compilers, especially older ones, will have implemented new in compliance with Standard C++. When C++ was first invented, new returned null on failure. Later, this was changed such that new caused an exception on failure. Finally, it was decided that a new failure will generate an exception by default, but that a null pointer could be returned instead, as an option.

Dynamic Allocation Operators

U4.94

95 of 136

int * b= new int [5];

  • In this case, the system dynamically assigns space for five elements of type int and returns a pointer to the first element of the sequence, which is assigned to b. Therefore, now, b points to a valid block of memory with space for five elements of type int.
  • The first element pointed by b can be accessed either with the expression b[0] or the expression *b. Both are equivalent.
  • The second element can be accessed either with b[1] or *(b+1) and so on...

�The dynamic memory requested by our program is allocated by the system from the memory heap. However, computer memory is a limited resource, and it can be exhausted. Therefore, it is important to have some mechanism to check if our request to allocate memory was successful or not.

Dynamic Allocation Operators

96 of 136

  • Pointer to objects of class, pointing to statically created objects.
  • Sample *ptr; Sample obj;
  • ptr=&obj;
  • ptr->x;
  • ptr->get();
  • Pointer to objects of the class, pointing to dynamically created objects.
  • Sample *ptr; ptr=new Sample;
  • ptr->x;
  • Ptr->get();

Delete ptr;

Dynamic Allocation Operators

U4.96

97 of 136

This program gives the allocated integer an initial value of 87:

#include <iostream> #include <new>

using namespace std;

int main()

{int *p;

try {p = new int (87); // initialize to 87

} catch (bad_alloc xa) {

cout << "Allocation Failure\n";

return 1;}

cout << "At " << p << " ";

cout << "is the value " << *p << "\n";delete p; return 0;}

U4.97

98 of 136

Compound Assignment Operator

// compound assignment operators

#include <iostream>

using namespace std;

int main ()

{

int a, b=3;

a = b;

a+=2; // equivalent to a=a+2

cout << a;

return 0;

}

O/P=5

U4.98

99 of 136

Conditional Operator

Conditional operator ( ? )

The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. Its format is:

condition ? result1 : result2

If condition is true the expression will return result1, if it is not it will return result2.

7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.

7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.

5>3 ? a : b // returns the value of a, since 5 is greater than 3.

a>b ? a : b // returns whichever is greater, a or b.

U4.99

100 of 136

Local and Global Variables

You can tell the compiler to use the global identifier rather than the local identifier by prefixing the identifier with ::, the scope resolution operator.

#include <iostream>

using namespace std;

int amount = 123; // A global variable

int main()

{

int amount = 456; // A local variable

cout << ::amount << endl // Print the global variable

cout<< amount << endl; // Print the local variable }

U4.100

101 of 136

Nesting of member function

Member function can be called by using its name inside another member function of the same class.

#include<iostream.h> #include<conio.h>

 class student

{ int age;

char name[30];

public:

void getdata();

void displaydata();

};

void student::getdata()

{ cout<<"\n enter the name:";

cin>>name;

cout<<"\n enter the age:";

cin>>age;

displaydata();}

void student::displaydata()

{

cout<<"\n\n name is:"<<name;

cout<<"\n age is:"<<age;}

 

void main()

{

student s;

s.getdata();

}

 

U4.101

102 of 136

Nested class

Class within the class and its calling method.

#include<iostream.h> #include<conio.h>

class report

{ int roll_no;char name[30], branch[30];

class dob

{ int dd, mm,yyyy;

public:

void get()

{cin>>dd>>mm>>yyyy; }

void display()

{ cout<<dd<<"-"<<mm<<"-"<<yyyy; }

}dob;

public:

void getdata();

void displaydata();};

U4.102

103 of 136

void report::getdata()

{cout<<"\nenter the roll no:"; cin>>roll_no;

cout<<"\nenter the name:"; cin>>name;

cout<<"\nenter the branch alloted:"; cin>>branch;

cout<<"\nenter the date of birth:";

dob.get();}

void report::displaydata()

{ cout<<"\n\nrollno\tname\tdate of birth\t branch alloted\n";

cout<<roll_no<<"\t"<<name<<"\t";

dob.display(); cout<<"\t\t"<<branch; }

void main()

{ report r;

r.getdata();

r.displaydata();

}

U4.103

104 of 136

Inline Functions

  • As you probably know, each time a function is called, a significant amount of overhead is generated by the calling and return mechanism. Typically, arguments are pushed onto the stack and various registers are saved when a function is called, and then restored when the function returns. The trouble is that these instructions take time.

  • However, when a function is expanded in line, none of those operations occur. Although expanding function calls in line can produce faster run times, it can also result in larger code size because of duplicated code.
  • To cause a function to be expanded in line rather than called, precede its definition with the inline keyword. For example, in this program, the function max( ) is expanded in line instead of called.

U4.104

105 of 136

#include <iostream>

using namespace std;

inline int max(int a, int b)

{

return a>b ? a : b;

}

int main()

{

cout << max(10, 20);

cout << " " << max(99, 88);

return 0;

}

As far as the compiler is concerned, the preceding program is equivalent to this one:

#include <iostream>

using namespace std;

int main()

{

return 0; cout << (10>20 ? 10 : 20);

cout << " " << (99>88 ? 99 : 88);

}

U4.105

106 of 136

Inline Functions

Inline functions may be class member functions. For example, this is a perfectly valid C++ program:

#include <iostream>

using namespace std;

class myclass {

int a, b;

public:

void init(int i, int j);

void show();

};

// Create an inline function.

inline void myclass::init(int i, int j)

{

a = i;

b = j;

}

// Create another inline function.

inline void myclass::show()

{

cout << a << " " << b << "\n";

}

int main()

{

myclass x;

x.init(10, 20);

x.show();

return 0;

}

U4.106

107 of 136

Defining Inline Functions Within a Class

When a function is defined inside a class declaration, it is automatically made into an inline function. It is not necessary (but not an error) to precede its declaration with the inline keyword.

U4.107

108 of 136

Example To Develop An Employee Class

/* class employee stores employee information. We use calc() function to return average salary. */

#include <iostream> #include <string> // to use strings

class employee

{private:

int emp_no, basic;

char name[20];

public:

void getdata() // to enter the data

{cout<<“Enter Employee No:”; cin>>emp_no;

cout<<“Enter name:”; cin.getline(name,’\n’);

cout<<“Enter Salary: “; cin>>basic;}

U4.108

109 of 136

Example To Develop An Employee Class

void dispdata() // to display the value

{cout<<“Employee no:”<<emp_no;

cout<<“Name:”<< name;

cout << “Salary: “<< basic;}

float calc(employee x) //parameter received

{float temp;

temp=(float(basic)+x.basic)/2;//int basic is casted to float

return temp;}}; // End of class declaration

void main()

{employee a1, b1; a1.getdata(); b1.getdata();

float average = a1.calc(b1);

cout<<endl<<“Average Salary:” <<average;}

U4.109

110 of 136

Defining constants (#define)

You can define your own names for constants that you use very often without having to resort to memory consuming variables, simply by using the #define preprocessor directive. Its format is:

#define identifier value

For example:

#define PI 3.14159

#define NEWLINE '\n'

U4.110

111 of 136

// defined constants: calculate circumference

#include <iostream>

using namespace std;

#define PI 3.14159

#define NEWLINE '\n'

int main ()

{

double r=5.0; // radius

double circle;

circle = 2 * PI * r;

cout << circle;

cout << NEWLINE;

return 0;

}

U4.111

112 of 136

U4.112

113 of 136

Variable Aliases- Reference Variables

  • Reference variable acts as an alias for the other value variables enjoys the simplicity of value variable and power of the pointer variable
  • Syntax

Datatype & ReferenceVariable = Value Variable

Ex: char & ch1 = ch;

  • References must be initialized to refer to something.
  • There is no such thing as a 0 reference.
  • Once bound to a variable there is no way to make the reference refer to something else.
  • There is no such thing as "reference arithmetic."

U4.113

114 of 136

Reference Variables contd..

  • You cannot get the address of a reference. You can try to, but what you get is the address of the variable referred to.
  • No alias for constant value

int &num = 100 //invalid

  • not bounded to a new memory location, but to the variables to which they are aliased
  • Function in C++ take arguments passed by reference

U4.114

115 of 136

Reference Variables cont..

#include <iostream.h>

void main(){

int a = 2;

int c = 7;

int& x = a;

cout<<a;

x = c;

cout <<a;

a=5;

int* b = &a;

cout<<a;

b = &c;

cout <<*b;}

U4.115

116 of 136

#include <iostream.h>

void swap1(int * a, int*b){

int temp = *a;

*a = *b;

*b = temp;

return;}

void swap2(int & a, int& b){

int temp = a;

a = b;

b = temp;

return;}

void main(){

int i =5;

int j = 10;

cout<< i <<" "<<j<<"\n";

swap1(&i, &j);

cout<< i <<" "<<j<<"\n";

swap2(i, j);

cout<< i <<" "<<j<<"\n";}

U4.116

117 of 136

Return by reference

  • Suppose we want to return the Max element, but prohibit the caller from changing it. Then we use a constant reference return:

const int & max(int & x, int & y)

#include <iostream.h>

int & max(int & x, int & y)

{

if (x>y)

return x;

else

return y;

}

void main(){

int a,b,c;

cout<<”enter <a,b>:”;

cin>>a>>b;

max(a,b) = 425;

cout<<”a=”<<a;

Cout<<” b= “<<b;}

U4.117

118 of 136

C++ Structures: Classes

  • In C++, the concept of structure has been generalized in an object-oriented sense:
    • classes are types representing groups of similar instances
    • each instance has certain fields that define it (instance variables)
    • instances also have functions that can be applied to them (represented as function fields) -- called methods
    • the programmer can limit access to parts of the class (to only those functions that need to know about the internals)

U4.118

119 of 136

Structs in C++

  • The C++ class is an extension of the C language structure.
  • The only difference between a structure and a class is that structure members have public access by default and class members have private access by default, you can use the keywords class or struct to define equivalent classes.
  • class X { // private by default

int a;

public: // public member function

int f() { return a = 5; }; };

  • struct Y { // public by default

int f() { return a = 5; };

private: // private data member

int a; };

U4.119

120 of 136

Static Instance Variables

  • C++ classes may also contain, static instance fields -- a single field shared by all members of a class
  • Often used when declaring class constants (since you generally only need one copy of a constant)
  • To make a field static, add the static keyword in front of the field
    • can refer to the field like any other field (but remember, everybody shares one copy)
    • static variables are also considered to be global, you can refer to them without an instance
    • static fields can be initialized (unlike other fields)
    • Ex: static int n=9;
  • One can examine public static fields of a class outside of that class using the form:

ClassName::StaticFieldName

U4.120

121 of 136

C++ Strings

  • The string class is part of the C++ standard library. A string represents a sequence of characters.
  • To use the string class, #include the header file: #include <string>
  • Constructors:
  • string () - creates an empty string ("")
  • string ( other_string ) - creates a string identical to other_string
  • string ( other_string, position, count ) �- creates a string that contains count characters from other_string, starting at position. If count is missing (only the first two arguments are given), all the characters from other_string, starting at position and going to the end of other_string, are included in the new string.
  • string ( count, character ) - create a string containing character repeated count times

U4.121

122 of 136

C++ Strings

  • Examples: �string s1; // s1 = "" �string s2( "abcdef" ); // s2 = "abcdef" �string s3( s2 ); // s3 = "abcdef" �string s4( s2, 1 ); // s4 = "bcdef" �string s5( s2, 3, 2 ); // s5 = "de" �string s6( 10, '-' ); // s6 = "----------" �The string class also has a destructor that takes care of freeing the memory storing the characters when the object is destroyed.

U4.122

123 of 136

Strings

  • Constant Member Functions: do not modify the string.
  • const char * data () - returns a C-style null-terminated string
  • unsigned int length () - returns the length of the string
  • unsigned int size () - returns the length of the string
  • bool empty () - returns true if the string is empty, false otherwise
  • Operators Defined for string:
  • Assign = �string s1; string s2; s1 = s2; // the contents of s2 is copied to s1
  • Append +=

string s1( "abc" ); string s2( "def" ); s1 += s2; // s1 = "abcdef" now

  • Indexing [] �string s( "def" ); char c = s[2]; // c = 'f' now

U4.123

124 of 136

Strings

  • Concatenate + �string s1( "abc" ); string s2( "def" );�string s3 = s1 + s2; // s3 = "abcdef" now
  • Equality == �string s1( "abc" ); string s2( "def" );�bool flag1 = ( s1 == s2 ); // flag1 = false now
  • Inequality != - the inverse of equality
  • Comparison <, >, <=, >= - performs case-insensitive comparison �string s1 = "abc"; string s2 = "ABC";�bool flag1 = ( s1 < s2 ); // flag1 = false now

U4.124

125 of 136

Member Functions:�

  • void swap ( other_string )

- swaps the contents of onestring with the contents of other_string. �string s1( "abc" ); string s2( "def" );s1.swap( s2 );

  • string & append ( other_string ) //appends other_string to this string, and returns a reference to the result string.
  • string & insert ( position, other_string ) // inserts other_string into this string at the given position, and returns a reference
  • string & erase ( position, count )

- removes count characters from this string, starting with the character at the given position. If count is omitted the characters up to the end of the string are removed. If both position and count are omitted the string is cleared.

  • unsigned int find ( other_string, position )
  • string substr ( position, count )

�-

U4.125

126 of 136

Pass-by-Value

  • A function can be invoked in two manners viz. pass-by-value and pass-by-reference . The pass-by-value method copies the actual parameters into the formal parameters, that is, the function makes its own copy of the argument and then uses them.
  • The main benefit of call-by-value method is that the original copy of the parameters remains intact and no alteration by the function is reflected on the original variable. All execution is done on the formal parameters; hence, it insures the safety of the data.
  • The drawback of call-by-value is that a separate copy of the arguments is used by the function, which occupies some memory space thus increasing the size of the program.

U4.126

127 of 136

Call-By-Reference

  • The call by reference uses a different mechanism. In place of passing value to the function, which is called, a reference to the original variable is passed.
  • A reference is an alias for the predefined variable. That is, the value of that variable can be accessed by using any of the two: the original or the reference variable name.
  • When a function is called by reference, then the formal parameters become reference to the actual parameters in the calling function. This means that, in call by reference method, the called function does not create its own copy of the original values, rather, it refers to the original values only by different names.
  • This called function works with the original data and any change in the value is reflected back to the data.

U4.127

128 of 136

Call-By-Reference in Functions

We use & to denote a parameter that is passed by reference:

Example:

  • The address (reference) of the actual variable is passed to the function, instead of its value.
  • If the function changes the parameter’s value, the change is reflected back in the actual variables in the called function, since they share the same memory location.

U4.128

129 of 136

Pass by Value / Pass by Reference

This program uses two functions, one using pass-by-value method and the other using pass-by-reference method.

This shows how the value of number does not change in the main function, when it is evaluated using pass-by-value method and on the other hand it changes when implemented using pass-by-reference method.

U4.129

130 of 136

Review Questions [Objective Types]

  1. Is it appropriate to call C++ as “better C”?
  2. What is the purpose of abstraction in C++?
  3. Why do people change over from structured programming to object programming approach?
  4. Is it necessary to use encapsulation feature to create class?
  5. What is the difference between Visual Basic and Visual C++?
  6. Inspite of so many object oriented languages, why did C++ become more popular?

U4.130

131 of 136

Review Questions [Objective Types]

  1. What is the difference between an object based language and an object-oriented language?
  2. What is the advantage of separating an interface from its implementation?
  3. What is the concept of multiple inheritance?
  4. I keep hearing that in structured programming data is given a step motherly treatment and the whole emphasis on doing thing. What that does mean in programmer’s language?

U4.131

132 of 136

Review Questions [Short Answer Types]

  1. How software crisis justifies the need for a new paradigm? Explain the various features of OO paradigm?
  2. Write an object representation (pictorial) of student class.
  3. What is the difference between inheritance and delegation? Illustrate with example.
  4. List different methods of realizing polymorphism and explain them with examples.
  5. Which is the first object oriented language? Explain the heritage of C++.

U4.132

133 of 136

Review Questions [Short Answer Types]

  1. Enumerate the important features of stream based I/O and provide a comparative analysis with its C counterpart statements such as scanf() and printf().
  2. Why are variables defined with const called as read-only variable? What are its benefits when compared to macros?
  3. What is name mangling? Is this transparent to user?
  4. What are the differences between reference variables and normal variables? Why can not constant value be initialized to variables of a reference type?
  5. Explain the need of type conversion with suitable examples.

U4.133

134 of 136

Review Questions [Long Answer Types]

  1. Describe the major parts of a C++ program. How does a main() functions in C++ differ from main() in C?
  2. List the various object oriented features supported by C++. Explain the constructs supported by C++ to implement them.
  3. What is polymorphism? Write a program to overload the + operator for manipulating objects of the Distance

Class.

  1. What are the different types of access specifiers supported by C++. Explain its need with the help of a suitable example.

U4.134

135 of 136

Review Questions [Long Answer Types]

  1. What are the differences between static binding and late binding ? Explain dynamic binding with a suitable example.
  2. Illustrate the use of inline function in A C++ program?

How it is different from MACROS? List its advantages and disadvantages also.

  1. What is inheritance? What are base class and derived class? Give a suitable example for inheritance
  2. What are generic classes? Explain how they are useful? Write an interactive program having template based Distance class. Create two objects: one of type integer and another of type float.

U4.135

136 of 136

Review Questions [Long Answer Types]

  1. What are exceptions? What are the constructs supported by C++ to handle exception.
  2. What are streams? Write an interactive program to copy a file to another file. Both source and destination files have to be processed as the objects of the file stream class.

U4.136