Oops Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 327

Object Oriented Programming in C++

Book to follow
• Object-Oriented Programming in C++, 4th Edition by Robert Lafore
• The C++ Programming Language, 4th Edition by Bjarne Stroustrup

2
UNIT I : Introduction to OOP
• Need of Object-Oriented Programming - Comparison of procedural
programming and Object-Oriented Programming
• Characteristics of Object-Oriented Languages
• C++ Programming Basics: Basic Program Construction
• Data Types, Variables, Constants
• Type Conversion, Operators, Library Functions
• Loops and Decisions, Structures
• Functions : Simple Functions, Passing arguments, Returning values,
Reference Arguments.
• Recursion, Inline Functions, Default Arguments
• Storage Classes
• Arrays , Strings

3
Programming paradigm
• Different approaches to build solutions to specific type of
problems

4
OOP Introduction
• Object-oriented programming (OOP) is a programming
paradigm based upon objects (having both data and methods)
that aims to incorporate the advantages of modularity and
reusability.

• Objects, which are usually instances of classes, are used to


interact with one another to design applications and computer
programs.

5
Procedural programming
• List of instructions to tell the computer what to do

6
Object oriented programming
• Component of a program that knows how to perform certain
actions and how to interact with other elements of the program

I am going to walk
(method)

7
Features of OOP
• Bottom–up approach in program design

• Programs organised around objects, grouped in classes

• Focus on data with methods to operate upon object’s data

• Interaction between objects through functions

• Reusability of design through creation of new classes by adding


features to existing classes

8
Comparison

Procedural Oriented Object Oriented

Program is divided into small parts Program is divided into small parts
called ‘Functions’ called ‘Objects’

Has access specifiers : Public,


Global and Local data
Private, Protected

Doesn’t have any proper way for


Provides data hiding and security
hiding data

Eg: C, VB, FORTAN Eg: C++, JAVA, VB.NET

9
Characteristics of Object-Oriented Languages
• Object
• Class
• Data Hiding and Encapsulation
• Dynamic Binding
• Message Passing
• Inheritance
• Polymorphism

10
C++ Programming Basics: Basic Program Construction
#include <iostream>
using namespace std;

// main() is where program execution begins.

int main()
{
cout << "Hello World"; // prints Hello World
return 0;
}

• Header files
• The line using namespace std; tells the compiler to use the std namespace.
Namespaces are a relatively recent addition to C++.
• Single line comment.
• The line int main() is the main function where program execution begins.
• The next line return 0; terminates main( )function and causes it to return the value 0 to
the calling process.

11
Compile and Execute
• Open a text editor and add the code.
• Save the file as: hello.cpp
• Open a command prompt / Terminal and go to the directory where
you saved the file.
• Type ‘g++ -o output hello.cpp’ and press enter to compile your code.
If there are no errors in your code the command prompt will take you
to the next line and would generate output executable file.
• Now, type ' ./output’ to run your program.

12
Basics
• In C++, the semicolon is a statement terminator.

• A C++ identifier is a name used to identify a variable, function,


class, module, or any other user-defined item. An identifier starts
with a letter A to Z or a to z or an underscore (_) followed by zero or
more letters, underscores, and digits (0 to 9).

• C++ does not allow punctuation characters such as @, $, and %


within identifiers.

• C++ is a case-sensitive programming language. (Thus, Name and


name are two different identifiers in C++)

13
C++ Keywords
Table 1 Keywords
asm else new this
auto enum operator throw
bool explicit private TRUE
break export protected try
case extern public typedef
catch FALSE register typeid
char float reinterpret_cast typename
class for return union
const friend short unsigned
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
do long struct wchar_t
double mutable switch while
dynamic_cast namespace template

14
Primitive Built-in Data Types
• Following table lists down six basic C++ data types:

Type Keyword

Boolean bool

Character char

Integer int

Floating point float

Double floating point double

Valueless void

• basic types can be modified using one or more of these type modifiers:
• signed
• unsigned
• short
• long

15
Data-types with its ranges
Type Typical Bit Width Typical Range

char 1byte -128 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -128 to 127

int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int 2bytes 0 to 65,535

signed short int 2bytes -32768 to 32767

long int 4bytes -2,147,483,648 to

signed long int 4bytes -2,147,483,648 to

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

float 4bytes +/- 3.4e +/- 38 (~7 digits)

double 8bytes +/- 1.7e +/- 308 (~15 digits)

long double 8bytes +/- 1.7e +/- 308 (~15 digits)

16
Example 1
#include <iostream>
using namespace std;

int main()
{
cout << "Size of char : " << sizeof(char) << endl; Size of char : 1
cout << "Size of int : " << sizeof(int) << endl; Size of int : 4
cout << "Size of short int : " << sizeof(short int) << endl; Size of short int : 2
cout << "Size of long int : " << sizeof(long int) << endl; Size of long int : 8
cout << "Size of float : " << sizeof(float) << endl; Size of float : 4
cout << "Size of double : " << sizeof(double) << endl; Size of double : 8
return 0;
}

17
C++ Variables
• A variable definition means to tell the compiler where and how much to
create the storage for the variable.

#include <iostream> datatype variable_list;


using namespace std;
int main () 30
{ 23.3333
// Variable definition:
int a, b;
int c;
float f;

// actual initialization
a = 10;
b = 20;
c = a + b;
f = 70.0/3.0;
cout<<c<<endl<<f;
return 0;
}
18
Declaration & Initialization
• Variable must be declared before they are used. Usually it is preferred
to declare them at the starting of the program, but in C++ they can be
declared in the middle of program too, but must be done before using
them.

int i; // declared but not initialised


char c;
int i, j, k; // Multiple declaration

int i; // declaration
i = 10; // initialization

int i=10; //initialization and declaration in same step


int i=10, j=11;

19
Scope of variables
• Global Variables
• Local variables

include <iostream>
using namespace std;
int x; // Global variable declared
int main()
{
int a; // Local variable declared
x=10; // Initialized once
cout <<"first value of x = "<< x;
x=20; // Initialized again
a=10; // Initialized once
cout <<"Initialized again with value = "<< x;
}

20
Special types of variable
• Final - Once initialized, its value cant be changed.
• Static - These variables holds their value between function calls.

#include <iostream.h>
using namespace std;
int main()
{
final int i=10;
static int y=20;
}

21
Constants
There are two simple ways in C++ to define constants:
• Using #define preprocessor. #define identifier value
• Using const keyword. const type variable = value;

#include <iostream> 50
using namespace std;

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{

int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
22
The const keyword
#include <iostream> 50
using namespace std;

int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;

area = LENGTH * WIDTH;


cout << area;
cout << NEWLINE;
return 0;
}

23
Type conversions
• A cast is a special operator that forces one data type to be converted
into another.
• Implicit type conversions
• Explicit type conversions

(type) expression

24
Explicit type conversions
#include <iostream> Line 1 - Value of (int)a is :21
using namespace std; Line 2 - Value of (int)b is :10

main()
{
double a = 21.09399;
float b = 10.20;
int c ;

c = (int) a;
cout << "Line 1 - Value of (int)a is :" << c << endl ;

c = (int) b;
cout << "Line 2 - Value of (int)b is :" << c << endl ;

return 0;
}

25
Implicit type conversions
#include <iostream> 2
0.1234
main()
{
int i = 2;
short s = i; // convert from int to short
std::cout << s;

double d = 0.1234;
float f = d;
std::cout << f;

return 0;
}

26
Operators
• Operators are special type of functions, that takes one or more
arguments and produces a new value.

27
Types of Operators
• Assignment Operator
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Unary Operators
• Ternary Operator
• Comma Operator

28
Operators
• Assignment Operator

Operates '=' is used for assignment, it takes the right-hand side (called rvalue)
and copy it into the left-hand side (called lvalue). Assignment operator is the
only operator which can be overloaded but cannot be inherited.

int x=10;

• Arithmetic Operators

Addition (+) , subtraction (-) , diversion (/) multiplication (*) and modulus (%) are
the basic mathematical operators. Modulus operator cannot be used with
floating-point numbers.

int x=10;
x += 4 // will add 4 to 10, and hence assign 14 to X.
x -= 5 // will subtract 5 from 10 and assign 5 to x.

29
Operators
• Relational Operators
These operators establish a relationship between operands. The relational
operators are : less than (<) , grater than (>) , less than or equal to (<=), greater
than equal to (>=), equivalent (==) and not equivalent (!=).

int x = 10; //assignment operator


x=5; // again assignment operator
if(x == 5) // equivalent relational operator, for comparison
{
cout <<"Successfully compared";
}

30
Operators
• Logical Operators

Operator Description Example

&& Called Logical AND operator. (A && B) is false.


If both the operands are non-
zero, then condition becomes
true.

|| Called Logical OR Operator. (A || B) is true.


If any of the two operands is
non-zero, then condition
becomes true.

! Called Logical NOT Operator. !(A && B) is true.


Use to reverses the logical
state of its operand. If a
condition is true, then Logical
NOT operator will make false.

31
Operators
• Bitwise operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are asfollows:

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

32
Operators A = 0011 1100
• Bitwise operators B = 0000 1101

Operator Description Example

& Binary AND Operator copies a bit to the result (A & B) will give 12 which is 0000
if it exists in both operands. 1100

| Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is 0011 1101
either operand.

^ Binary XOR Operator copies the bit if it is set (A ^ B) will give 49 which is 0011
in one operand but not both. 0001

~ Binary Ones Complement Operator is unary (~A ) will give -61 which is 1100 0011
and has the effect of 'flipping' bits. in 2's complement form due to a
signed binary number.

<< Binary Left Shift Operator. The left operands A << 2 will give 240 which is 1111
value is moved left by the number of bits 0000
specified by the right operand.
>> Binary Right Shift Operator. The left operands A >> 2 will give 15 which is 0000
value is moved right by the number of bits 1111
specified by the right operand.

33
Operators
• Unary Operators

These are the operators which work on only one operand. There are many unary
operators, but increment ++ and decrement -- operators are most used.

• Ternary Operator

The ternary if-else ? : is an operator which has three operands.

int a = 10;
a > 5 ? cout << "true" : cout << “false";

• Comma Operator

This is used to separate variable names and to separate expressions. In case of


expressions, the value of last expression is produced and used.

int a,b,c; // variables declaration using comma operator

34
Library Functions
• This functions perform file access, mathematical computations
and data conversions, among other things.
Table 1 Mathematical Functions (cmath)
Function Meaning
sin(x) Sine of an angle x (measured in radians)
cos(x) Cosine of an angle x (measured in radians)
tan(x) Tangent of an angle x (measured in radians)
asin(x) Sin-1 (x) where x (measured in radians)
acos(x) Cos-1 (x) where x (measured in radians)
exp(x) Exponential function of x (ex)

log(x) logarithm of x

log 10(x) Logarithm of number x to the base 10


sqrt(x) Square root of x
pow(x, y) x raised to the power y
abs(x) Absolute value of integer number x
fabs(x) Absolute value of real number x

35
Library Functions
Table 2 Character Functions (cctype)
Function Meaning

isalpha(c) It returns True if C is an uppercase letter and False if c is


lowercase.
isdigit(c) It returns True if c is a digit (0 through 9) otherwise False.

isalnum(c) It returns True if c is a digit from 0 through 9 or an alphabetic


character (either uppercase or lowercase) otherwise False.
islower(c) It returns True if C is a lowercase letter otherwise False.

isupper(c) It returns True if C is an uppercase letter otherwise False.

toupper(c) It converts c to uppercase letter.

tolower(c) It converts c to lowercase letter.

36
Decision Making
Decision making is about deciding the order of execution of statements
based on certain conditions or repeat a group of statements until certain
specified conditions are met. C++ handles decision-making by
supporting the following statements,
• if statement
• switch statement
• conditional operator statement
• goto statement

37
Decision Making with if statement
The if statement may be implemented in different forms depending on
the complexity of conditions to be tested. The different forms are,
• Simple if statement
• If....else statement
• Nested if....else statement
• else if statement

int a = 5;
if(a > 4)
cout << "success";

if(27)
cout << "hello";

38
Looping
• In any programming language,
loops are used to execute a set of
statements repeatedly until a
particular condition is satisfied.
• There are 3 type of loops in C++
language
• while loop
• for loop
• do-while loop

39
while loop
• while loop can be address as an entry control loop. It is completed in
3 steps.
variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}

40
for loop
• for loop is used to execute a set of statement repeatedly until a
particular condition is satisfied. we can say it an open ended loop.
General format is,

for(initialization; condition ; increment/decrement)


{
statement-block;
}

• Nested for loop


for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
}
}
41
do while loop
• do statement evaluates the body of the loop first and at the end, the
condition is checked using while statement.

do
{
....
.....
}
while(condition);

42
Jumping out of loop
• break : When break statement is encountered inside a loop, the
loop is immediately exited and the program continues with the
statement immediately following the loop.

• continue : It causes the control to go directly to the test-condition


and then continue the loop process.

43
C++ structures
• Structure is the collection of variables of different types under a
single name for better visualisation of problem.

struct person
{
char name[50];
int age;
float salary;
};

• How to define a structure variable?


person bill;

44
#include <iostream>
Structure Example 1 using namespace std;

struct person {
Enter Full name: Magdalena Dankova char name[50];
Enter age: 27 int age;
Enter salary: 1024.4 float salary;
};
Displaying Information. int main() {
Name: Magdalena Dankova
Age: 27 person p1;
Salary: 1024.4
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

return 0;
}
45
C++ Functions
• Functions are used to provide modularity to a program. Creating
an application using function makes it easier to understand, edit,
check errors etc.
• Library functions
• User defined functions

return-type function-name (parameters)


{
// function-body
}

46
Declaring, Defining and Calling Function
#include < iostream>
using namespace std;

int sum (int x, int y); //declaring function

int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling function
cout << c;
}

int sum (int x, int y) //defining function


{
return (X + y);
}

47
Calling a function
• Functions are called by their names. If the function is without
argument, it can be called directly using its name. But for
functions with arguments, we have two ways to call them,
• Call by Value
• Call by Reference

48
Call by value
#include < iostream>
#include < iostream>
using namespace std;
using namespace std;
void calc(int x);
int calc(int x);
int main() int main()
{ {
int x = 10; int x = 10;
calc(x); x = calc(x);
cout<<x; printf("%d", x);
} }

void calc(int x) int calc(int x)


{ {
x = x + 10 ; x = x + 10 ;
} return x;
}

10 20

49
Call by reference
#include < iostream>
using namespace std;

void calc(int *p);

int main()
{
int x = 10;
calc(&x); // passing address of x as argument
printf("%d", x);
}

void calc(int *p)


{
*p = *p + 10;
}

20

50
Recursion
• In recursion, a function calls itself until condition is satisfied.
#include <iostream> Enter a number to find factorial: 4
using namespace std; Factorial of 4 = 24
int factorial(int);

int main() {
int n;
cout<<"Enter a number to find factorial: ";
cin>>n;
cout<<"Factorial of "<<n<<" = "<<factorial(n);
return 0;
}

int factorial(int n) {
if (n>1) {
return n*factorial(n-1);
}
else {
return 1;
}
}
51
How recursion works?

52
Inline functions
• C++ inline function is powerful concept that is commonly used
with classes. If a function is inline, the compiler places a copy of
the code of that function at each point where the function is
called at compile time.

53
Inline function Example 1
#include <iostream> Max (20,10): 20
Max (0,200): 200
using namespace std; Max (100,1010): 1010

inline int Max(int x, int y)


{
return (x > y)? x : y;
}

// Main function for the program


int main( )
{

cout << "Max (20,10): " << Max(20,10) << endl;


cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}

54
Default arguments

55
Default arguments Example 1
#include <iostream>
using namespace std;
No argument passed:
void display(char = '*', int = 1);
*
First argument passed:
int main() {
#
cout<<"No argument passed:\n"; Both argument passed:
display(); $$$$$
cout<<"\n\nFirst argument passed:\n";
display('#');
cout<<"\n\nBoth argument passed:\n";
display('$', 5);
return 0;
}

void display(char c, int n){


for(int i = 1; i <=n; ++i) {
cout<<c;
}
cout<<endl;
}
56
Storage Classes
• Storage classes are used to specify the lifetime and scope of
variables. How storage is allocated for variables and How
variable is treated by complier depends on these storage
classes.
• These are basically divided into 5 different types :
• Global variables
• Local variables
• Register variables
• Static variables
• Extern variables

• Global variables
• These are defined at the starting , before all function bodies and are
available throughout the program.

57
Storage Classes
• Local variables
• They are defined and are available within a particular scope.
They are also called Automatic variable.

• Register variables
• This is also a type of local variable. This keyword is used to tell
the compiler to make access to this variable as fast as
possible. Variables are stored in registers to increase the
access speed.

58
Storage classes
• Static variable
• Static variables are the variables which are initialized &
allocated storage only once

void fun()
{
static int i = 10;
i++;
cout << i;
}
int main()
{
fun(); // Output = 11
fun(); // Output = 12
fun(); // Output = 13
}

59
Storage classes
• Extern variables
• This keyword is used to access variable in a file which is
declared & defined in some other file, that is the existence of a
global variable in one file is declared using extern keyword in
another file.

60
Arrays
• An array is a sequence of variable that can store value of one
particular data type.

• Defining Arrays : type array_name[size];

int age[5];

• Array Initialization : int age[5] = {12, 3, 4, 3, 9};

• It is not necessary to write the size of an array during array


declaration.

int age[ ] = {12, 3, 4, 3, 9};

61
Arrays Example 1
include <iostream> Enter 5 numbers: 4
using namespace std; -3
5
int main() 2
{ 0
int n[5]; First number: 4
cout<<"Enter 5 numbers: “; Last number: 0

/* Storing 5 number entered by user in an array using for loop. */

for (int i = 0; i < 5; ++i) {


cin>>n[i];
}

cout<<"First number: "<<n[0]<<endl; // first element of an array is n[0]


cout<<"Last number: "<<n[4]; // last element of an array is n[SIZE_OF_ARRAY - 1]
return 0;
}

62
C++ Multidimensional Arrays
• C++ allows programmer to create array of an array known as
multidimensional arrays.

• int x[3][4];

63
Two Dimensional Arrays Example 1
#include <iostream> test[0][0] = 2
using namespace std; test[0][1] = -5
test[1][0] = 4
int main() test[1][1] = 0
{ test[2][0] = 9
int test[3][2] = { test[2][1] = 1
{2, -5},
{4, 0},
{9, 1}
};

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


{
for(int j = 0; j < 2; ++j)
{
cout<< "test["<< i << "][" << ;j << "] = " << test[i][j]<<endl;
}
}
return 0;
}
64
Strings
• Two types of strings:
• Strings that are objects of string class (The Standard C++ Library string class
• C-strings (C-style Strings)

char str[] = "C++";


• str is a string and it holds 4 character. Although, "C++" has 3 character, the null
character \0 is added to the end of the string automatically.

• Other ways of defining the string:


char str[4] = "C++";

char str[] = {'C','+','+','\0'};

char str[4] = {'C','+','+','\0'};

65
C- Strings
S.No Function & Purpose

1 strcpy(s1, s2); Copies string s2 into string s1.

2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.

3 strlen(s1); Returns the length of string s1.

strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if


4
s1<s2; greater than 0 if s1>s2.
strchr(s1, ch); Returns a pointer to the first occurrence of character
5
ch in string s1.
strstr(s1, s2); Returns a pointer to the first occurrence of string s2
6
in string s1.
66
C-Strings Example 1
#include <iostream> Enter a string: C++
using namespace std; You entered: C++

int main() { Enter another string: Programming is fun.


char str[100]; You entered: Programming
cout<<"Enter a string: ";
cin>>str;
cout<<"You entered: "<<str<<endl;
cout<<"\nEnter another string: ";
cin>>str;
cout<<"You entered: "<<str<<endl;
return 0;
}

67
C-Strings Example 2 #include <iostream>
#include <cstring>

using namespace std;

int main ()
{
char str1[10] = "Hello";
strcpy( str3, str1) : Hello char str2[10] = "World";
strcat( str1, str2): HelloWorld char str3[10];
strlen(str1) : 10 int len ;

// copy str1 into str3


strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation


len = strlen(str1);
cout << "strlen(str1) : " << len << endl;

return 0;
}
68
#include <iostream>
String Class Example 3 #include <string>

using namespace std;

str3 : Hello int main ()


str1 + str2 : HelloWorld {
str3.size() : 10 string str1 = "Hello";
string str2 = "World";
string str3;
int len ;

// copy str1 into str3


str3 = str1;
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;

// total lenghth of str3 after concatenation


len = str3.size();
cout << "str3.size() : " << len << endl;

return 0;
}
69
Object Oriented Programming
Book to follow
• Object-Oriented Programming in C++, 4th Edition by Robert Lafore
• The C++ Programming Language, 4th Edition by Bjarne Stroustrup

2
UNIT 2 : Features of Object Oriented Programming
• Introduction to Classes and Objects
• Constructors and its types, Destructors
• Passing Objects as Function arguments and Returning Objects from
Functions
• Operator Overloading
• Inheritance
• Overloading Member Functions
• Pointers
• Virtual Functions – Friend Functions, Static Functions

3
You will learn about the following in this chapter :

• Member functions and data


• private and public
• Constructors and Destructors
• When to use objects
• Objects in real world

4
Introduction to classes
• The classes are the most important feature of C++ that leads to Object
Oriented programming.
• Class is a user defined data type, which holds its own data members and
member functions, which can be accessed and used by creating
instance of that class.

5
More about classes
• Class name must start with an uppercase letter. If class name is made of more
than one word, then first letter of each word must be in uppercase.

Example, class Study

• Classes contain, data members and member functions, and the access of these
data members and variable depends on the access specifiers.

• Class's member functions can be defined inside the class definition or outside
the class definition.

• Class in C++ are similar to structures in C, the only difference being, class
defaults to private access control, where as structure defaults to public.

• All the features of OOPS, revolve around classes in C++. Inheritance,


Encapsulation, Abstraction etc.

• Objects of class holds separate copies of data members. We can create as many
objects of a class as we need.

6
Objects
• Class is mere a blueprint or a template. No storage is assigned when we
define a class.
• Objects are instances of class, which holds the data variables declared
in class and the member functions work on these class objects.
• Objects are initialised using special class functions called Constructors.
We will study about constructors later.
• And whenever the object is out of its scope, another special class
member function called Destructor is called, to release the memory
reserved by the object.
• C++ doesn't have Automatic Garbage Collector like in JAVA, in C++
Destructor performs this task.

7
Class and Objects Example 1
#include <iostream> Number: 12
using namespace std; Enter data: 12.43
class temp You entered: 12.43
{
private:
int data1;
float data2;
public:
void int_data(int d){
data1=d;
cout<<"Number: "<<data1;
}
float float_data(){
cout<<"\nEnter data: ";
cin>>data2;
return data2;
}
};
int main(){
temp obj1, obj2;
obj1.int_data(12);
cout<<"You entered "<<obj2.float_data();
return 0;
}
8
Access control in classes
• public
• private
• protected

• These access specifiers are used to set boundaries for availability of


members of class be it data members or member function.

• public : A public member is accessible from anywhere outside the class


but within a program.

• private : A private member variable or function cannot be accessed, or


even viewed from outside the class. Only the class and friend functions
can access private members.

• protected : A protected member variable or function is very similar to a


private member but it provided one additional benefit that they can be
accessed in child classes which are called derived classes
9
Access Specifiers Example 1
#include <iostream> // Main function for the program
using namespace std;
int main( )
class Line {
{ Line line;
public:
double length; // set line length
void setLength( double len ); line.setLength(6.0);
double getLength( void ); cout << "Length of line : " << line.getLength() <<endl;
};
// set line length without member function
double Line::getLength(void)
{ line.length = 10.0; // OK: because length is public
return length ; cout << "Length of line : " << line.length <<endl;
} return 0;
}
void Line::setLength( double len )
{
length = len; Length of line : 6
} Length of line : 10

10
Access Specifiers Example 2
#include <iostream>
// Main function for the program
using namespace std; int main( )
{
class Box Box box;
{
public: // set box length without member function
double length; box.length = 10.0; // OK: because length is public
void setWidth( double wid ); cout << "Length of box : " << box.length <<endl;
double getWidth( void );
// set box width without member function
private: // box.width = 10.0; // Error: because width is private
double width; box.setWidth(10.0); // Use member function to set it.
}; cout << "Width of box : " << box.getWidth() <<endl;

// Member functions definitions return 0;


double Box::getWidth(void) }
{
return width ;
}
Length of box : 10
void Box::setWidth( double wid ) Width of box : 10
{
width = wid;
}
11
Access Specifiers Example 3
#include <iostream> void SmallBox::setSmallWidth( double wid )
using namespace std; {
width = wid;
class Box }
{
protected: // Main function for the program
double width; int main( )
}; {
SmallBox box;
class SmallBox:Box
{ // set box width using member function
public: box.setSmallWidth(5.0);
void setSmallWidth( double wid ); cout << "Width of box : "<< box.getSmallWidth();
double getSmallWidth( void );
}; return 0;
}
// Member functions of child class
double SmallBox::getSmallWidth(void)
{ Width of box : 5
return width ;
}

12
Constructors
• Constructors are special class functions which performs
initialization of every object.
• The Compiler calls the Constructor whenever an object is created.

class A
{
int x;
public:
A(); //Constructor
};

• While defining a constructor you must remember that the name of


constructor will be same as the name of the class, and contractors
never have return type.

13
Constructors Example 1
#include <iostream> int main()
using namespace std; {
class Area Area A1,A2;
{ int temp;
private: A1.GetLength();
int length; temp=A1.AreaCalculation();
int breadth; A1.DisplayArea(temp);

public: cout<<endl<<"Default Area when value is


Area(): length(5), breadth(2){ } /* Constructor */ not taken from user”<<endl;
void GetLength()
{ temp=A2.AreaCalculation();
cout<<"Enter length and breadth respectively: "; A2.DisplayArea(temp);
cin>>length>>breadth; return 0;
} }
int AreaCalculation() { return (length*breadth); }
void DisplayArea(int temp) Enter length and breadth respectively: 6
{ 7
cout<<"Area: "<<temp; Area: 42
} Default Area when value is not taken from
}; user
Area: 10

14
Constructor Overloading Example 2
#include <iostream> int main()
using namespace std; {
class Area Area A1,A2;
{ int temp;
private: A1.GetLength();
int length; temp=A1.AreaCalculation();
int breadth; A1.DisplayArea(temp);

public: cout<<endl<<"Default Area when value is


Area(): length(5), breadth(2){ } not taken from user”<<endl;
Area(int l, int b): length(l), breadth(b){ }
void GetLength() temp=A2.AreaCalculation();
{ A2.DisplayArea(temp);
cout<<"Enter length and breadth respectively: "; return 0;
cin>>length>>breadth; }
}
int AreaCalculation() { return (length*breadth); } Enter length and breadth respectively: 6
void DisplayArea(int temp) 7
{ Area: 42
cout<<"Area: "<<temp<<endl; Default Area when value is not taken from
} user
}; Area: 10

15
Types of Constructors
• Default Constructor
• Parametrised Constructor
• Copy Constructor

• Default Constructor
• Default constructor is the constructor which doesn't take any
argument. It has no parameter.

class_name ()
{
Constructor Definition
}

16
Default Constructor Example 1

class Cube class Cube


{ {
int side; int side;
public: };
Cube()
{ int main()
side=10; {
} Cube c;
}; cout << c.side;
}
int main()
{
Cube c;
cout << c.side;
}

Output : 10 Output : 0

17
Parametrised Constructor
• These are the constructors with parameter. Using this Constructor
you can provide different values to data members of different
objects, by passing the appropriate values as argument.

18
Parametrised Constructor Example 1

class Cube OUTPUT : 10 20 30


{
int side;
public:
Cube(int x)
{
side=x;
}
};

int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}

19
Copy Constructor
• These are special type of Constructors which takes an object as
argument, and is used to copy values of data members of one
object into other object.

20
Copy Constructor Example 1

int main()
#include<iostream>
{
using namespace std;
Point p1(10, 15);
Point p2 = p1;
class Point
{
cout << "p1.x = " << p1.getX() << ", p1.y =
private:
" << p1.getY();
int x, y;
cout << "\np2.x = " << p2.getX() << ",
public:
p2.y = " << p2.getY();
Point(int x1, int y1) { x = x1; y = y1; }
return 0;
// Copy constructor
}
Point(Point &p2) {x = p2.x; y = p2.y; }

int getX() { return x; }


int getY() { return y; }
};
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15

21
Destructors
• A destructor is a special member function of a class that is
executed whenever an object of it's class goes out of scope or
whenever the delete expression is applied to a pointer to the object
of that class.

class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration

private:
double length;
};

22
Passing Objects as Function arguments

23
Passing Objects as Function arguments Example 1
#include <iostream>
using namespace std; int main()
class Complex {
{ Complex c1,c2,c3;
private: c1.Read();
int real; c2.Read();
int imag; c3.Add(c1,c2);
public: c3.Display();
Complex(): real(0), imag(0) { } return 0;
void Read() }
{
cout<<"Enter real and imaginary number respectively:";
cin>>real>>imag;
}
void Add(Complex comp1,Complex comp2) Enter real and imaginary
{ number respectively:
real=comp1.real+comp2.real;
imag=comp1.imag+comp2.imag; 12
} 3
void Display() Enter real and imaginary
{ number respectively:
cout<<"Sum="<<real<<"+"<<imag<<"i";
2
}
}; 6
Sum=14+9i
24
Returning Object from Functions

25
Returning Object from Functions Example 1
#include <iostream> int main()
using namespace std; {
class Complex Complex c1,c2,c3;
{ c1.Read();
private: c2.Read();
int real; int imag; c3=c1.Add(c2);
public: c3.Display();
Complex(): real(0), imag(0) { } return 0;
void Read() }
{
cin>>real>>imag;
}
Complex Add(Complex comp2)
{
Complex temp;
temp.real=real+comp2.real;
temp.imag=imag+comp2.imag;
return temp;
}
void Display()
{
cout<<"Sum="<<real<<"+"<<imag<<"i";
}
};

26
Operator Overloading
• Operator overloading is an important concept in C++. It is a type of
polymorphism in which an operator is overloaded to give user
defined meaning to it.
• Overloaded operator is used to perform operation on user-defined
data type.
• For example '+' operator can be overloaded to perform addition on
various data types, like for Integer, String(concatenation) etc.
• This feature in C++ programming that allows programmer to
redefine the meaning of operator when they operate on class
objects is known as operator overloading.

27
Operator that are not overloaded are follows

• scope operator ::
• sizeof
• member selector .
• member pointer selector *
• ternary operator ?:

Types :
• Binary Operator Overloading

• Unary Operator Overloading

28
Binary Operator Overloading Example 1

#include<iostream> complex operator + (complex c2)


{
class complex complex temp;
{ temp.real=this.real+c2.real;
public: temp.imag=this.imag+c2.imag;
int real,imag; return temp;
}
void display() };
{
cout<<real<<imag; void main()
} {
complex a,b,c;
void input() a.input();
{ b.input();
cin>>real>>imag; c=a+b;
} c.display();
return 0;
}

29
Unary Operator Overloading Example 1
#include<iostream> void display()
class complex {
{ cout<<a<<"+\t"<<b<<"i"<<endl;
int a,b,c; }
public: };
void getvalue()
{
cout<<"Enter the Two Numbers:";
cin>>a>>b; int main()
} {
complex obj;
void operator++() obj.getvalue();
{ obj++;
a=++a; b=++b; cout<<"Increment Complex Number\n";
} obj.display();
obj--;
void operator--() cout<<"Decrement Complex Number\n";
{ obj.display();
a=—a; b=--b; return 0;
} }

30
Inheritance
• The mechanism that allows us to extend the definition of a class
without making any physical changes to the existing class is
inheritance.
• Inheritance lets you create new classes from existing class.
• Any new class that you create from an existing class is called
derived class; existing class is called base class.
• The inheritance relationship enables a derived class to inherit
features from its base class. Furthermore, the derived class can
add new features of its own.
• Therefore, rather than create completely new classes from scratch,
you can take advantage of inheritance and reduce software
complexity.

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

32
Types of Inheritance

33
How to use Inheritance ?
• In order to derive a class from another, we use a colon (:) in the
declaration of the derived class using the following format :

class derived_class: memberAccessSpecifier base_class


{
...
};

34
How Members of the Base Class Appear in the Derived Class
Member Access How Members of the Base Class Appear in the Derived Class
Specifier
Private Private members of the base class are inaccessible to the derived class.

Protected members of the base class become private members of the


derived class.
Public members of the base class become private members of the
derived class.
Protected Private members of the base class are inaccessible to the derived class.

Protected members of the base class become protected members of the


derived class.
Public members of the base class become protected members of the
derived class.
Public Private members of the base class are inaccessible to the derived class.

Protected members of the base class become protected members of the


derived class.
Public members of the base class become public members of the
derived class.

35
Inheritance Example 1

36
Inheritance Example 1
#include <iostream> class Triangle: public Shape
{
class Shape public:
{
protected: float area ()
float width, height; {
public: return (width * height / 2);
void set_data (float a, float b) }
{ };
width = a;
height = b; int main ()
} {
}; Rectangle rect;
Triangle tri;
class Rectangle: public Shape rect.set_data (5,3);
{ tri.set_data (2,5);
public: cout << rect.area() << endl;
float area () cout << tri.area() << endl;
{ return 0;
return (width * height); }
}
};
15
5
37
Constructor and Inheritance
• The compiler automatically calls a base class constructor before
executing the derived class constructor. The compiler’s default action is
to call the default constructor in the base class.

• You can specify which of several base class constructors should be


called during the creation of a derived class object.

• This is done by specifying the arguments to the selected base class


constructor in the definition of the derived class constructor.

38
Constructor and Inheritance Example 1
class Rectangle class Box : public Rectangle
{ {
private :
private : float height;
float length; public:
float width; Box () { height = 0; }
Box (float len, float wid, float ht) : Rectangle(len, wid)
public: {
Rectangle () height = ht;
{ }
length = 0;
width = 0; float volume()
} {
return area() * height;
Rectangle (float len, float wid) }
{ };
length = len;
width = wid; int main ()
} {
Box bx;
float area() Box cx(4,8,5);
{ cout << bx.volume() << endl; 0
return length * width ; cout << cx.volume() << endl; 160
} return 0;
}; }
39
Overriding Base Class Functions
• A derived class can override a member function of its base class by
defining a derived class member function with the same name and
parameter list.

• It is often useful for a derived class to define its own version of a member
function inherited from its base class.

• This may be done to specialize the member function to the needs of the
derived class. When this happens, the base class member function is
said to be overridden by the derived class

40
Overriding Base Class Functions
class mother
{ daughter: display function
public:
void display ()
{
cout << "mother: display function\n";
}
};

class daughter : public mother


{
public:
void display ()
{
cout << "daughter: display function\n\n";
}
};

int main ()
{
daughter rita;
rita.display();
return 0;
}
41
Gaining Access to an Overridden Function
class daughter : public mother
{
public:
void display ()
{
cout << "daughter: display function\n\n";
mother::display();
}
};

daughter: display function


mother: display function

42
Virtual Base Class
• Multi-path inheritance may lead to duplication of inherited members from
a grandparent base class. This may be avoided by making the common
base class a virtual base class. When a class is made a virtual base
class, C++ takes necessary care to see that only one copy of that class
is inherited.

43
Virtual Base Class
class A
{
.....
.....
};

class B1 : virtual public A


{
.....
.....
};

class B2 : virtual public A


{
.....
.....
};

class C : public B1, public B2


{
.....// only one copy of A
.....// will be inherited
};

44
Pointers
• To understand pointers, you should have the knowledge of address
in computer memory.
• Computer memory is broken down into bytes and each byte has its
own address. For example: In 1KB memory, there are 1024 bytes
and each byte is given an address (0 - 1023).
• A pointer is a variable whose value is the address of another
variable.
type *var-name;

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

45
Pointers Example 1
#include <iostream>
Value of var variable: 20
using namespace std; Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";


cout << var << endl;

// print the address stored in ip pointer variable


cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}
46
Pointers Detail

Concept Description

C++ N u ll C++ supports null pointer, which is a constant with a value of zero defined in
Pointers several standard libraries.

C+ + p oin ter There are four arithmetic operators that can be used on pointers: ++, --, +, -
arithmetic

C++ pointers vs There is a close relationship between pointers and arrays. Let us check how?
arrays

C+ + a r r a y of You can define arrays to hold a number of pointers.


pointers

C++ pointer to C++ allows you to have pointer on a pointer and so on.
pointer

Passing pointers Passing an argument by reference or by address both enable the passed
to functions argument to be changed in the calling function by the called function.

Return pointer C++ allows a function to return a pointer to local variable, static variable and
from functions dynamically allocated memory as well.

47
Null Pointer
• It is always a good practice to assign the pointer NULL to a pointer
variable in case you do not have exact address to be assigned. This is
done at the time of variable declaration. A pointer that is assigned NULL
is called a null pointer.

#include <iostream> The value of ptr is 0

using namespace std;

int main ()
{
int *ptr = NULL;

cout << "The value of ptr is " << ptr ;

return 0;
}

48
C++ pointer arithmetic
#include <iostream> Address of var[0] = 0xbfa088b0
Value of var[0] = 10
using namespace std; Address of var[1] = 0xbfa088b4
const int MAX = 3; Value of var[1] = 100
Address of var[2] = 0xbfa088b8
int main () Value of var[2] = 200
{
int var[MAX] = {10, 100, 200};
int *ptr;

// let us have array address in pointer.


ptr = var;
for (int i = 0; i < MAX; i++)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;

// point to the next location


ptr++;
}
return 0;
} 49
C++ pointers vs arrays
#include <iostream> Address of var[0] = 0xbfa088b0
Value of var[0] = 10
using namespace std; Address of var[1] = 0xbfa088b4
const int MAX = 3; Value of var[1] = 100
int main ()
Address of var[2] = 0xbfa088b8
{ Value of var[2] = 200
int var[MAX] = {10, 100, 200};
int *ptr;

// let us have array address in pointer.


ptr = var;
for (int i = 0; i < MAX; i++)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;

// point to the next location


ptr++;
}
return 0;
} 50
C++ array of pointers
#include <iostream> Value of var[0] = 10
Value of var[1] = 100
using namespace std; Value of var[2] = 200
const int MAX = 3;

int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr[MAX];

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


{
ptr[i] = &var[i]; // assign the address of integer.
}
for (int i = 0; i < MAX; i++)
{
cout << "Value of var[" << i << "] = ";
cout << *ptr[i] << endl;
}
return 0;
}

51
C++ pointer to pointer
#include <iostream> Value of var :3000
Value available at *ptr :3000
using namespace std; Value available at **pptr :3000
int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;

// take the address of var


ptr = &var;

// take the address of ptr using address of operator &


pptr = &ptr;

// take the value using pptr


cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;

return 0;
}
52
Passing pointers to functions
#include <iostream> double getAverage(int *arr, int size)
using namespace std; {
int i, sum = 0;
// function declaration: double avg;
double getAverage(int *arr, int size);
for (i = 0; i < size; ++i)
int main () {
{ sum += arr[i];
// an int array with 5 elements. }
int balance[5] = {1000, 2, 3, 17, 50};
double avg; avg = double(sum) / size;

// pass pointer to the array as an argument. return avg;


avg = getAverage( balance, 5 ) ; }

// output the returned value Average value is: 214.4


cout << "Average value is: " << avg << endl;

return 0;
}

53
Return pointer from functions
#include <iostream>
using namespace std; int main()
{
double & GetWeeklyHours() double hours = GetWeeklyHours();
{ double salary = *GetSalary();
double h = 46.50;
double &hours = h; cout << "Weekly Hours: " << hours << endl;
cout << "Hourly Salary: " << salary << endl;
return hours;
} double WeeklySalary = hours * salary;

double * GetSalary() cout << "Weekly Salary: " << WeeklySalary << endl;
{
double salary = 26.48; return 0;
double *HourlySalary = &salary; }

return HourlySalary;
} Weekly Hours: 46.5
Hourly Salary: 26.48
Weekly Salary: 1231.32

54
Friend function
• A friend function of a class is defined outside that class' scope but it has
the right to access all private and protected members of the class. Even
though the prototypes for friend functions appear in the class definition,
friends are not member functions.

• A friend can be a function, function template, or member function, or a


class or class template, in which case the entire class and all of its
members are friends.

55
Friend function Example 1
#include <iostream> void printWidth( Box box )
{
using namespace std;
cout << "Width of box : " << box.width <<endl;
class Box }
{
double width; int main( )
public: {
friend void printWidth( Box box ); Box box;
void setWidth( double wid ); box.setWidth(10.0);
}; printWidth( box );

void Box::setWidth( double wid ) return 0;


{ }
width = wid;
}
Width of box : 10

56
Static Functions
• Static is a keyword in C++ used to give special characteristics to an
element. Static elements are allocated storage only once in a program
lifetime in static storage area. And they have a scope till the program
lifetime.

57
Static Function Example 1
class IDGenerator The next ID is: 1
{ The next ID is: 2
private: The next ID is: 3
static int s_nextID; The next ID is: 4
The next ID is: 5
public:
static int getNextID();
};

// We'll start generating IDs at 1


int IDGenerator::s_nextID = 1;

int IDGenerator::getNextID() { return s_nextID++; }

int main()
{
for (int count=0; count < 5; ++count)
cout << "The next ID is: " << IDGenerator::getNextID() << '\n';

return 0;
}

58
UNIT 3
CONSTRUCTORS AND OVERLOADING
CONSTRUCTOR
A constructor is 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 constructs the values of data members of
the class
CHARACTERISTICS
 They should be declared in the public section.
 They are invoked automatically when the objects
are created.
 They do not have return types, not even void and
therefore, and they cannot return values.
 They cannot be inherited, though a derived class
can call the base class constructor.
 Like other C++ functions, they can have default
arguments.
CONSTRUCTOR
A constructor is declared and defined as follows.
class integer
{
int m, n ; public :
integer (void ) ;
};
integer : : integer(void )
{
m=o ; n=o ;
cout <<”m=”<<m<<” n=”<<n ;
}
void main( )
{
integer int ;
}
Output:-
m=0 n=0
PARAMETERIZED CONSTRUCTORS

C++ permits us to achieve this objective by passing


arguments to the constructor function when the
objects are created. The constructors that can take
arguments are called parameterized constructors.
We must pass the initial values as arguments to
the constructor function when an object is
declared. This can be done in two ways.
❑ By calling the constructor explicitly integer
int1=integer(0,100);
 By calling the constructor implicitly integer
int1(0,100);
Example
#include<iostream.h> class sample
{
int m, n ;
public:
sample( int, int ) ;
};
sample : : sample (int x, int y )
{
; n=y ;
m=x cout<<m<<n ;
}

void main ( )
{
}
Output:-
sample S(25,50);
25 50
MULTIPLE CONSTRUCTOR
class integer
{
int m, n ; public :
integer( )
{
m=0;n=0;
cout<<m<<n<<endl ;
}
integer ( int a, int b )
{
m=a;n=b;
cout<<m<<n ;
}
integer(integer &i )
{
m = i. m ;
n = i. n ;
}
};
void main( )
{
integer int1 ; integer int2( 10, 20) integer int3(int1) ;
}
Output:-
00
10 20
10 20
COPY CONSTRUCTOR
A constructor can accept a reference to its own class as a parameter.
class A
{
………….
…………….
…………….. public :
A(A&) ;
};
is valid. In such cases, the constructor is called copy constructor.
A copy constructor takes a reference to an object of the same
class as itself as an argument. Let us consider a simple example
of constructing and using a copy constructor as shown in the
following program
Example
#include<iostream.h> class code
{ int main ( )
int id ; public :
{
code( )
code A ( 100 ) ; code B (A ) ; code C = A ;
{
code D ;
}
code(int a)
D=A:
{ cout<<”/n id of A : “ ;
id = a; display ( ) ; cout<<”/n id of B : “ ;
} display ( ) ; cout<<”/n id of C : “ ;
code(code &x)
{ display ( ) ; cout<<”/n id of D : “ ;
id = x. id ;
display ( ) ; return 0 :
}
void display( void )
}
{ Output:-
cout<<id ; id of A:100 id of B:100 id of C:100 id of
} D:100
};
Multiple Choice Question
Which among the following best describes constructor
overloading?
a) Defining one constructor in each class of a
program
b) Defining more than one constructor in single class
c) Defining more than one constructor in single class
with different signature
d) Defining destructor with each constructor
Answer: c
Multiple Choice Question
Can constructors be overloaded in derived class?
a) Yes, always
b) Yes, if derived class has no constructor
c) No, programmer can’t do it
d) No, never

Answer: d
Multiple Choice Question
Does constructor overloading include different return
types for constructors to be overloaded?
a) Yes, if return types are different, signature
becomes different
b) Yes, because return types can differentiate two
functions
c) No, return type can’t differentiate two functions
d) No, constructors doesn’t have any return type

Answer: d
Multiple Choice Question
Which among the following is possible way to overload
constructor?
a) Define default constructor, 1 parameter constructor
and 2 parameter constructor
b) Define default constructor, zero argument constructor
and 1 parameter constructor
c) Define default constructor, and 2 other
parameterized constructors with same signature
d) Define 2 default constructors

Answer : a
Multiple Choice Question
Which among the following is false for a constructor?
a) Constructors doesn’t have a return value
b) Constructors are always user defined
c) Constructors are overloaded with different
signature
d) Constructors may or may not have any arguments
being accepted
Answer: b
DESTRUCTOR
It is used to destroy the objects that have been
created by a constructor. Like a constructor, the
destructor is a member function whose name is the
same as the class name but is preceded by a tilde.
~integer( )
{
-----------
}
Example
#include<iostream.h> int count = 0 ;
class alpha
{
alpha ( )
{
cout<< “ object created “
}
~ alpha ( )
{
cout<< “ object destroyed ;
}
int main( )
{
alpha A1 ; }
Output:- object created
object destroyed
Multiple Choice Question
When is the constructor called for an object?
a) As soon as overloading is required
b) As soon as class is derived
c) As soon as class is created
d) As soon as object is created

Answer : d
Multiple Choice Question
Which among the following function can be used to
call default constructor implicitly in java?
a) this()
b) that()
c) super()
d) sub()

Answer: a
Multiple Choice Question
Why do we use constructor overloading?
a) To use different types of constructors
b) Because it’s a feature provided
c) To initialize the object in different ways
d) To differentiate one constructor from another

Answer: c
Multiple Choice Question
If programmer have defined parameterized constructor
only, then __________________
a) Default constructor will not be created by the
compiler implicitly
b) Default constructor will be created by the compiler
implicitly
c) Default constructor will not be created but called at
runtime
d) Compile time error

Answer:a
Multiple Choice Question

What are we only create an object but don’t call any


constructor for it in java?
a) Implicit constructor will be called
b) Object is initialized to some null values
c) Object is not created
d) Object is created but points to null

Answer: d
SCOPE RESOLUTION OPERATOR
Blocks and scopes can be used in construction programs.
We know that the same variable name can be used to
have different meanings in different blocks. The scope
of the variable extends from the point of its declaration
till the end of the block containing the declaration. A
variable declared inside a block is said to be local to
that block. In C , the global version of a variable cannot
be accessed from within the inner block. In C++
resolves this problem by introducing a new operator :: is
called the scope resolution operator. This can be used to
uncover a hidden variable. It takes the following form.
:: variable-name
Program for scope resolution
operator
#include<iostream.h> int m=10;// global m void main()
{
int m=20;//m redeclared, local to main
{
int k=m;
int m=30;//m declared again, local to inner block cout<<”we are inner block
\n”; cout<<”k=”<<k<<”\n”;
cout<<”m=”<<m<<”\n”;

cout<<”::m”<<:: m<<”\n”;
}
cout<<”\n we are in outer block \n”; cout<<”m=”<<m<<”\n”;
cout<<”::m”<<::m<<”\n”;
}
Output
we are in inner block k=20
m=30
::m=20
we are in outer block m=20
::m=10
MEMORY MANAGEMENT
OPERATORS
C++ supports two unary operators new and delete that
perform the task of allocating and freeing the
memory. An object can be created by using new, and
destroyed by using delete. C++ uses a unique
keyword called this to represent an object that invokes
a member function. This is a pointer that points to
the object for which this function was called.
int *p = new int ;
We can also initialize the memory using the new operator.
pointer-variable = new data-type(value);
int *p = new int (25);
float *q = new float ( 7.5 );
DELETE
When a data object is no longer needed it is
destroyed to release the memory space for reuse.
delete pointer-variable ;
delete p ; delete q
MANIPULATORS
Manipulators are operators that are used to format
the data display.
The most commonly used manipulators are end l and
set w.
endl -->
when used in an output statement , causes a
linefeed to be inserted. It has the same effect as
using the newline character “ \ n “.
Example
cout << setw(5) <<sum << end l ;
setw(5) specifies a field width 5 for printing the value
of the variable sum. The value is right justified
within the field
Multiple Choice Question
Which among the following is false?
a) Constructor can’t be overloaded in Kotlin
b) Constructors can’t be called recursively in java
c) Constructors can be overloaded in C++
d) Constructors overloading depends on different
signatures

Answer : a
Multiple Choice Question
Which among the following is called first,
automatically, whenever an object is created?
a) Class
b) Constructor
c) New
d) Trigger

Answer: b
Multiple Choice Question
Which among the following is not a necessary
condition for constructors?
a) Its name must be same as that of class
b) It must not have any return type
c) It must contain a definition body
d) It can contains arguments

Answer: c
Multiple Choice Question
Which among the following is correct?
a) class student{ public: int student(){} };
b) class student{ public: void student (){} };
c) class student{ public: student{}{} };
d) class student{ public: student(){} };

Answer: d
Multiple Choice Question
In which access should a constructor be defined, so
that object of the class can be created in any
function?
a) Public
b) Protected
c) Private
d) Any access specifier will work

Answer: a
PROGRAM
#include <iostream .h> #include <iomanip.h> int main( )
{
int Basic = 950 ;
int Allowance = 95 ; int Total = 1045 ;
cout << setw(10)<< “Basic” <<setw (10) << Basic <<
endl
<< setw(10)<< “Allowance “ <<
setw(10)<<Allowance<<endl
<< setw(10)<<”Total”<<setw(10)<< Total << endl ;
return 0 :
}
TYPE CAST OPERATOR
C++ permits explicit type conversion of variables or
expressions using the type cast operator.
( type-name ) expression -€c type-name (expression ) -€
c ++
Example :-
Average = sum /(float)i ; Average = sum /float(i) ;
FRIEND FUNCTION
A function that has access to the private member of
the class but is not itself a member of the class is
called friend functions.The general form is
friend data_type function_name( );
Friend function is preceded by the keyword ‘friend’.
Consider a situation of operating on objects of two
different classes, in such situation, friend function
can be used to bridge the two classes.
Example
#include<iostream.h>
class result; //advance declaration class test
{
int n1,n2; public:
void getmark( )
{ n1=45; n2=78;
}
friend void display( test, result); // friend function declaration
};
class result
{
int tot; public:
friend void display(test,result); // friend function declaration
};
void display( test t, result r)
{
ot= t.n1+t.n2; // private member of test class accessed using t object

cout<<r. tot;
}
void main( )
{
test t; result r;
t.getmark( );
display( t, r);
}
EXPLANATION
The program contains two classes test and result.
The display function is friend function to access the private data
members of both the classes.
Declaration of the friend function can be placed either in the
private or public section of the class.
An object of each class has been passed as an argument to the
function display (
)
It can access the private members of both classes through these
arguments.
The advanced declaration of the class result; in the beginning of
the program is necessary, since a class cannot be referred until
it has been declared before the class test.
USES OF FRIEND FUNCTION
 Function operating on objects of two different
classes.
 Friend function can be used to increase the
versatility of overloaded operators.
EXPLANATION
 Class two is friend to class one, so all the private
members of class one can be accessed in member
function of class two using class one object.
 Here addone () and display () functions using the
private data members of class one. So both the
functions are having argument as object of class
one.
THIS POINTER
C++ uses a unique keyword called this to represent
an object that invokes a member function. This is a
pointer that points to the object for which this
function was called.
OVERLOADING IN C++
❑ Function overloading
❑ Types of function overloading
❑ Operator overloading
❑ Overloading unary operator and Overloading
binary operator.
❑ Templates
❑ Generic functions and Generic classes
FUNCTION
 A function is a set of instructions that are used to
perform specified tasks which repeatedly occurs
in the main program.
 By using function we can divide complex tasks into
manageable tasks. The function can also help to
avoid duplication of work.
Call by value
This method copies the values of actual parameters
into the formal parameters of the function, because
formal arguments are photocopy of actual
arguments. Changes made in the formal arguments
are local to the block of the called functions.
Once control returns back to the calling function
the changes made disappear.
Example
#include<iostream.h> class call
{
int a; public:
void getdata (int p)
{
a=p; cout<< a;
}
};
void main ( )
{
call c; int x;
c.getdata (3) }
Return by value
#include<iostream.h> class call
{
int a; public:
int getdata (int p)
{
a=p; return p;
}
};
void main ( )
{
call c int x;
x=c.getdata (3); cout<<x;
}
Call by reference
Call by reference is another way of passing
parameters to the function. Here, the address of
arguments are copied into the parameters
inside the function, the address is used to access
the actual arguments used in the call. Hence
changes made in the arguments are permanent
Example
#include<iostream.h> class sample
{
int t; public:
void swap (int & a, int & b)
{
t=a; a=b; b=t;
}
};
void main ( )
{
sample s;
int i=5, j=10, k; k = s. swap (i, j); cout<<k;
}
i, j €it will pass the value of i&j .
& a, & b€ it will take the address of a & b [i.e., x, y]
*a, * b-€ it takes the value of a & b.
#include<iostream.h>
class sample
{
int t ; public:
{
}
};
void swap (int *a, int * b) t = * a;
*a= * b;
*b= t;

void main ( )
{
sample s; int x, y; cin>>x>>y;
s.swap (&x, &y)
)
&x, &y, pass address value
*a, *b€takes the value of x & y
Return by reference
A function can also return a reference. #include<iostream.h>
class sample
{
public:
int &max (int &x, int &y)
{
if(x > y) return x; else return y;
}
};
void main()
{
sample S,T; T=S.max(5,2)
cout<<”greater”<<T;
}
Output:-
greater 5
FUNCTION OVERLOADING
We can use the same function name to create
functions that perform a variety of different tasks.
This is known as function polymorphism in oop. Using the
concept of function overloading, we can design a family
of functions with one function name but with different
argument lists.
The function would perform different operations
depending on the argument list in the function call.
The correct function to be invoked is determined by
checking the number and type of the arguments but
not on the function type.
Example
 Declarations:-
 int add (int a, int b);
 int add (int a, int b, int c);
 double add (double x, double y);
 double add (int p, double q);
 double add (double p, int q);
OPERATOR OVERLOADING
 C ++ has the ability to provide the operators with
a special meaning for a data type. The mechanism
of giving such special meanings to an operator is
known as operator overloading.
 The process of overloading involves the following steps:
 Create a class that defines the data type that is to be
used in the overloading operation.
 Declare the operator function operator op()in the public
part of the class
 It may be either a member function or a friend function
 Define the operator function to implement the required
operations.
OPERATOR OVERLOADING
Syntax:-
returntype classname:: operator op (argument list)
{
Function body
}.
Example:-
void space:: operator-( )
{
x=-x;
}
OVERLOADING UNARY OPERATORS

 Let us consider the unary minus operator. A minus


operator when used as a unary takes just one
operand.
 We know that this operator changes the sign of an
operand when applied to a basic data item.
 We will see here how to overload this operator so
that it can be applied to an object in much the same
way as is applied to an int or float variable.
 The unary minus when applied to an object should
change the sign of each of its data items.
Note
 The function operator-() takes no argument. Then,
what does this operator
 function do? It changes the sign of data members of
the object S. Since this function is a member function
of the same class, it can directly access the members
of the object which activated it
OVERLOADING BINARY OPERATORS

 The same mechanism which is used in overloading


unary operator can be used to overload a binary
operator
Multiple Choice Question
How many types of constructors are available for use
in general (with respect to parameters)?
a) 2
b) 3
c) 4
d) 5

Answer: a
Multiple Choice Question
If a programmer defines a class and defines a default value
parameterized constructor inside it.
He has not defined any default constructor. And then he try
to create the object without passing arguments, which
among the following will be correct?
a) It will not create the object (as parameterized constructor
is used)
b) It will create the object (as the default arguments are
passed)
c) It will not create the object (as the default constructor is
not defined)
d) It will create the object (as at least some constructor is
defined)
Answer: b
Multiple Choice Question
If class C inherits class B. And B has inherited class A.
Then while creating the object of class C, what will
be the sequence of constructors getting called?
a) Constructor of C then B, finally of A
b) Constructor of A then C, finally of B
c) Constructor of C then A, finally B
d) Constructor of A then B, finally C

Answer: d
Multiple Choice Question
Which among the following is true for copy
constructor?
a) The argument object is passed by reference
b) It can be defined with zero arguments
c) Used when an object is passed by value to a
function
d) Used when a function returns an object

Answer: b
Multiple Choice Question
If the object is passed by value to a copy constructor?
a) Only public members will be accessible to be
copied
b) That will work normally
c) Compiler will give out of memory error
d) Data stored in data members won’t be accessible
Answer: c
Multiple Choice Question
Which among the following helps to create a
temporary instance?
a) Implicit call to a default constructor
b) Explicit call to a copy constructor
c) Implicit call to a parameterized constructor
d) Explicit call to a constructor

Answer: d
Construct
•Constructors are special class functions which performs
ors
initialization of every object.
• The Compiler calls the Constructor whenever an object is created.

class A
{
int x;
public:
A(); //Constructor
};

• While defining a constructor you must remember that the name of


constructor will be same as the name of the class, and contractors
never have return type.
Constructors
Example 1
#include <iostream>
using namespace std;
class Area
int main()
{
Area A1,A2;
{ int temp;
private: A1.GetLength();
int length; temp=A1.AreaCalculation();
int breadth; A1.DisplayArea(temp);

public: cout<<endl<<"Default Area when value is


Area(): length(5), breadth(2){ } /* Constructor */ not taken from user”<<endl;
void GetLength()
{ temp=A2.AreaCalculation();
cout<<"Enter length and breadth respectively: "; A2.DisplayArea(temp);
cin>>length>>breadth; return 0;
} }
int AreaCalculation() { return (length*breadth); }
void DisplayArea(int temp) Enter length and breadth respectively: 6
{ 7
cout<<"Area: "<<temp; Area: 42
} Default Area when value is not taken from
}; user
Area: 10

65
Constructor Overloading
Example 2
#include <iostream>
using namespace std;
class Area
int main()
{
Area A1,A2;
{ int temp;
private: A1.GetLength();
int length; temp=A1.AreaCalculation();
int breadth; A1.DisplayArea(temp);

public: cout<<endl<<"Default Area when value is


Area(): length(5), breadth(2){ } not taken from user”<<endl;
Area(int l, int b): length(l), breadth(b){ }
void GetLength() temp=A2.AreaCalculation();
{ A2.DisplayArea(temp);
cout<<"Enter length and breadth respectively: "; return 0;
cin>>length>>breadth; }
}
int AreaCalculation() { return (length*breadth); } Enter length and breadth respectively: 6
void DisplayArea(int temp) 7
{ Area: 42
cout<<"Area: "<<temp<<endl; Default Area when value is not taken from
} user
}; Area: 10
Types of
Constructors


Default Constructor
Parametrised Constructor
• Copy Constructor

• Default Constructor
• Default constructor is the constructor which doesn't take any
argument. It has no parameter.

class_name ()
{
Constructor Definition
}
Default Constructor
Example 1
class Cube
{
class Cube
{
int side; int side;
public: };
Cube()
{ int main()
side=10; {
} Cube c;
}; cout << c.side;
}
int main()
{
Cube c;
cout << c.side;
}

Output : 10 Output : 0
Parametrised
Constructor
• These are the constructors with parameter. Using this Constructor
you can provide different values to data members of different
objects, by passing the appropriate values as argument.
Parametrised Constructor
Example 1
class Cube
{
OUTPUT : 10 20 30
int side;
public:
Cube(int x)
{
side=x;
}
};

int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
Copy
Constructor

These are special type of Constructors which takes an object as


argument, and is used to copy values of data members of one
object into other object.
Copy Constructor
Example 1
#include<iostream>
int main()
{
using namespace std;
Point p1(10, 15);
Point p2 = p1;
class Point
{
private: cout << "p1.x = " << p1.getX() << ", p1.y =
" << p1.getY();
int x, y;
cout << "\np2.x = " << p2.getX() << ",
public:
p2.y = " << p2.getY();
Point(int x1, int y1) { x = x1; y = y1; }
return 0;
// Copy constructor
}
Point(Point &p2) {x = p2.x; y = p2.y; }

int getX() { return x; }


int getY() { return y; }
};
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15
Destruct
ors
•A destructor is a special member function of a class that is
executed whenever an object of it's class goes out of scope or
whenever the delete expression is applied to a pointer to the object
of that class.

class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration

private:
double length;
};

73
Passing Objects as Function
arguments

74
Passing Objects as Function
#include <iostream>

arguments Example 1
using namespace std;
class Complex
{
int main()
{
Complex c1,c2,c3;
private: c1.Read();
int real; c2.Read();
int imag; c3.Add(c1,c2);
public: c3.Display();
Complex(): real(0), imag(0) { } return 0;
void Read() }
{
cout<<"Enter real and imaginary number respectively:";
cin>>real>>imag;
}
void Add(Complex comp1,Complex comp2) Enter real and
{
imaginary number
real=comp1.real+comp2.real;
imag=comp1.imag+comp2.imag; respectively:
} 12
void Display() 3
{ Enter real and
cout<<"Sum="<<real<<"+"<<imag<<"i";
}
imaginary number
}; respectively:
2
6
Returning Object from
Functions
Returning Object from
Functions Example 1
#include <iostream>
using namespace std;
class Complex
int main()
{
Complex c1,c2,c3;
{ c1.Read();
private: c2.Read();
int real; int imag; c3=c1.Add(c2);
public: c3.Display();
Complex(): real(0), imag(0) { } return 0;
void Read() }
{
cin>>real>>imag;
}
Complex Add(Complex comp2)
{
Complex temp;
temp.real=real+comp2.real;
temp.imag=imag+comp2.imag;
return temp;
}
void Display()
{
cout<<"Sum="<<real<<"+"<<imag<<"i";
}
};
Operator
Overloading

Operator overloading is an important concept in C++. It is a type of



polymorphism in which an operator is overloaded to give user
defined meaning to it.

Overloaded operator is used to perform operation on user-defined
data type.


For example '+' operator can be overloaded to perform addition on
various data types, like for Integer, String(concatenation) etc.
This feature in C++ programming that allows programmer to

redefine the meaning of operator when they operate on class


objects is known as operator overloading.
Operator that are not
overloaded

are
scope operator ::
follows
• sizeof
• member selector .
• member pointer selector *
• ternary operator ?:

Types :
• Binary Operator Overloading

• Unary Operator Overloading


Binary Operator
Overloading Example 1
#include<iostream> complex operator + (complex c2)
{
class complex complex temp;
{ temp.real=this.real+c2.real;
public: temp.imag=this.imag+c2.imag;
int real,imag; return temp;
}
void display() };
{
cout<<real<<imag; void main()
} {
complex a,b,c;
void input() a.input();
{ b.input();
cin>>real>>imag; c=a+b;
} c.display();
return 0;
}
Unary Operator
Overloading Example 1
#include<iostream>
class complex
void display()
{
{ cout<<a<<"+\t"<<b<<"i"<<e
ndl;
int a,b,c; }
public: };
void getvalue()
{
cout<<"Enter the Two
Numbers:";
cin>>a>>b; int main()
} {
complex obj;
void operator++() obj.getvalue();
{ obj++;
a=++a; b=++b; cout<<"Increment Complex
Number\n";
} obj.display();
obj--;
void operator--() cout<<"Decrement Complex
Number\n";
UNIT 5
I/O AND LIBRARY ORGANIZATION
FILE HANDLING

 File handling is an important part of all programs. Most of the


applications need to save some data to the local disk and read
data from the disk again. C++ File I/O classes simplify such file
read/write operations for the programmer by providing easier to
use classes.
 The I/O system of C++ uses file s tre am s as an interface between
the program and the files during file operations.
 The stream that supplies data to the program is known as inpu t
s tre am
 The one that receives data from the program is known as ou tpu t
s tre am .
 In other words, the input stream reads data from the file and the
output stream writes data
FILE HANDLING
File Input and Output Streams

 The input operation involves the creation of an


in pu t s tre am and linking the input file with the
program. The input stream extracts (reads) the data
from the file and supplies to the program.
 Similarly, the output operation involves establishing
an ou tpu t s tre am and making necessary links with
the program and the output file. The output stream
receives data from the program and stores or
inserts (writes) the data into the file.
DATA FILES
 Sequential Access Files: These files must be accessed in the same
order in which they were written. This process is analogous to audio
cassette tapes where you must fast forward or rewind through the
songs sequentially to get to a specific song. In order to access data
from a sequential file, you must start at the beginning of the file and
search through the entire file for the data that you want.

 Random Access Files: These files are analogous to audio compact


disks where you can easily access any song, regardless of the order
in which the songs were recorded. Random access files allow instant
access to any data in the file. Unfortunately, random access files
often occupy more disk space than sequential access files.
Multiple Choice Question
In memory-mapped I/O ____________
a) The I/O devices and the memory share the same
address space
b) The I/O devices have a separate address space
c) The memory and I/O devices have an associated
address space
d) A part of the memory is specifically set aside for
the I/O operation
Multiple Choice Question

The usual BUS structure used to connect the I/O devices is ___________
a) Star BUS structure
b) Multiple BUS structure
c) Single BUS structure
d) Node to Node BUS structure

Answer: c
Multiple Choice Question
The advantage of I/O mapped devices to memory
mapped is ___________
a) The former offers faster transfer of data
b) The devices connected using I/O mapping have
a bigger buffer space
c) The devices have to deal with fewer address lines
d) No advantage as such

Answer: c
Multiple Choice Question
The system is notified of a read or write operation by
___________
a) Appending an extra bit of the address
b) Enabling the read or write bits of the devices
c) Raising an appropriate interrupt signal
d) Sending a special signal along the BUS

Answer : d
Multiple Choice Question
To overcome the lag in the operating speeds of the
I/O device and the processor we use ___________
a) BUffer spaces
b) Status flags
c) Interrupt signals
d) Exceptions

Answer : b
File Streams
 C++ program views input (or output) as a stream
of bytes. On input, a program extracts (>>) bytes
from an input stream. On output, a program inserts
(<<) bytes into the output stream. The stream acts
as a mediator between the program and the
stream's source or destination.
 A buffer is a block of memory used as an
intermediate, temporary storage area for the
transfer of information between a program and a
device
File Streams
Creating a Sequential Access File
 A file is a container for data. which needs to be
opened and closed. Before you can put
 something into a file, or take something out, you
must open the file (the drawer). When you are
finished using the file, the file (the drawer) must be
closed
File Stream Classes:
 C++ provides the following classes to perform input
and output of characters to /
 from files:
 ifstream : Stream class to read from files
 ofstream : Stream class to write on files
 fstream : Stream class to both read and write from/to
files
 These file stream classes are designed exclusively to
manage the disk files and their declaration exists in the
header file fs tre am .h, therefore we must include this
header file in any program that uses files
File Stream Classes:
 These classes are derived directly or indirectly from the classes
is tre am , and os tre am .
 The actions performed by the stream classes related to file
management are:
 ifstream: The class ifstream supports input operations. It contains
open( ) with default input mode and inherits get( ) , getline( ) , read(
) , seekg( ) , and tellg( ) functions from is tre am .
 ofstream: The class ofstream supports output operations. It contains
open( ) with default output mode and inherits put( ) , write( ) , seekp(
) , and tellp( ) functions from os tre am
 fstream: The class fstream supports simultaneous input and output
operations. It contains open ( ) with default input mode and inherits
all functions from is tre am an d os tre am classes through ios tre am
Opening and Closing of Files :
Manipulation of a file involves the following
steps:
 Name the File on the disk
 Open the File

 Process the File ( Read / Write)

 Check for Errors while processing

 Close the File


File name:
 The Filename is a string of characters, with which a file
is logically identified by the user. The number of
characters used for the file name depends on the
Operating system. Normally a filename contains two
parts, a nam e and an exte n s ion . The extension is
optional.
 In MS-DOS systems, the maximum size of a file name is
eight characters and that of an extension is three
characters. In UNIX based systems, the file name can be
up to 31 characters and any number of extensions
separated by a dot.
Opening a File
 A file can be opened either in Read, Write or
Append mode. For opening a file, we must first
create a file stream and then link it to the filename.
A file can be opened in two ways:
 Using Constructor function of the class.
 Using the member function open ( ) of the class.
 The first method is useful when we use only on e file
in the stream. The second method is used when we
want to mange m u ltiple files using one stream.
Opening files using Constructors:
We know that a constructor is used to initialize an object
while it is being created. Here, the constructor can be
utilized to initialize the file name to be used with the
file stream object. The creation and assignment of file
name to the file stream object involves the following
steps:
 Create a file stream object using the appropriate class.
For example, ofs tre am can be used to create the
output stream, ifs tre am for input stream and fs tre am
can be used to create input and output stream.
 Initialize the object with the desired filename
Opening File in Write Mode:
Example:
#include <fstream.h>
void main()
{
ofstream myfile("example.txt”); myfile<< "Hello World!"; myfile.close( );
}
This code creates a file called example.txt and inserts a sentence “Hello World” into it using the
file stream myfile.
In the above example,
ofstream myfile (“example.txt”);
ofstream means “output file stream”. It creates an object for a file stream to write in a file.
myfile –the name of the object. The object name can be any valid C++ name.
(“example.txt”); - opens the file example.txt, which should be placed in the directory from where
you execute the program. If such a file does not exist, it will be created for you.
Opening File in Write Mode:
In order to open a file with a stream object we use its member function open():
Syntax: open (filename, mode);
Where filename is a null-terminated character sequence of type const char * (the same type that
string literals have) representing the name of the file to be opened, and mode is an optional
parameter with a combination of the following flags:
ios::in Open for input operations. ios::out Open for output operations. ios::binary Open in
binary mode.
Set the initial position at the end of the file.
ios::ate
ios::app
ios::trunc

If this flag is not set to any value, the initial position is the beginning of the file.
All output operations are performed at the end of the file, appending the content to the current
content of the file. This flag can only be used in streams open for output-only operations.
If the file opened for output operations already existed before, its previous content is deleted
and replaced by the new one.
Closing a file
 When we are finished with our input and output
operations on a file we shall close it so that its resources
become available again. In order to do that we have to
call the stream's member function close(). This member
function takes no parameters, and what it does is to
flush the associated buffers and close the file:
 myfile.close();
 Once this member function is called, the stream object
can be used to open another file, and the file is
available again to be opened by other processes.
INPUT/OUTPUT OPERATIONS ON
FILES:
The functions, put(), and get(), are designed to manage a
single character at a time.
The other functions, read(), write(), are designed to
manipulate blocks of character data.
put( ), and get( ) functions:
The function get( ) is a member function of the file stream
class fstream, and is used to read a single character
from the file.
The function put( ) is a member function of the output
stream class fstream, and is used to write a single
character to the output file.
Multiple Choice Question
The method of accessing the I/O devices by
repeatedly checking the status flags is
___________
a) Program-controlled I/O
b) Memory-mapped I/O
c) I/O mapped
d) None of the mentioned

Answer: a
Multiple Choice Question
The method of synchronising the processor with the
I/O device in which the device sends a signal when
it is ready is?
a) Exceptions
b) Signal handling
c) Interrupts
d) DMA

Answer: c
Multiple Choice Question
The method which offers higher speeds of I/O
transfers is ___________
a) Interrupts
b) Memory mapping
c) Program-controlled I/O
d) DMA

Answer: d
Multiple Choice Question
The process wherein the processor constantly checks
the status flags is called as ___________
a) Polling
b) Inspection
c) Reviewing
d) Echoing

Answer: a
Exception Handling:-
 Exceptions are runtime anomalies or unusual conditions that
a program may encounter while executing. Anomalies might
include conditions such as division by zero, access to an
array outside of its bounds, or running out of memory or
disk space.
 Exceptions are of two kinds, namely, synchronous exceptions
and asynchronous exceptions. Errors such as “out-of-range”
and “overflow” belong to the synchronous type exceptions.
The errors that are caused by events beyond the control of
the programs(such as keyboard interrupts) are called
asynchronous exceptions. The proposed exception handling
mechanism in C++ is designed to handle only synchronous
exceptions.
Exception Handling:-
The purpose of the exception handling mechanism is
to provide means to detect and report an
“exceptional circumstance” so that appropriate
action can be taken. The mechanism suggests a
separate error handling code that performs the
following tasks.
 Find the problem(Hit the exception)
 Inform that an error has occurred(throw the exception)
 Receive the error information(catch the exception)

 Take corrective actions(Handle the exception


Exception Handling:-
 Exception handling mechanism is basically built upon
three keywords, namely, try,throw, and catch. The
keyword try is used to preface a block of statements
which may generate exceptions. This block of
statements is known as try block.
 When an exception is detected , it is thrown using a
throw statement in the try block. A catch block defined
by the keyword catch, catches the exception thrown by
the throw statement in the try block, and handles it
appropriately. The catch block that catches an
exception must immediately follow the try block that
throws the exception.
Exception Handling Model:
 The exception handling mechanism uses three blocks
try, throw, catch. The relationship of those three
exception handling model shown below
Exception Handling Model:
Exception Handling Model:
 The keyword try is used to preface a block of
statements (surrounded by braces) which may
generate exceptions. This block of statements known
as try bock.
 When an exception is detected, it is thrown using a
throw statement in the try block.
 A catch block defined by the keyword catch catches
the exception thrown by the throw statement in the
try block, and handle it appropriately.
Exception Handling Model:
 When the try block throws an exception, the program control leaves the try block
and enters the catch statement of the catch block.
 Exceptions are objects or variables used to transmit information about a problem.
 If the type of object thrown matches the arg type in the catch statement, then catch
block is executed for handling the exception.
 If they do not match, the program is aborted with the help of the abort() function
which is invoked automatically.
 The catch block may have more than one catch statements, each corresponding to a
particular type of exception.
 For example if the throw block is likely to throw two exception, the catch block will
have two catch statements one for each type of exception. Each catch statement is
called is exception handler.
 When no exception is detected and thrown, the control goes to the statement
immediately after the catch block. That is catch block is skipped.
 Example: divide by zero
Catch All Exceptions:
 In some situations, we may not be able to anticipate
all possible types of exceptions and therefore may
not be able to design independent catch handlers
to catch them, IN such circumstances, we can force a
catch statement to catch all exceptions instead of a
certain type alone. This could be achieved by
defining the catch statement using ellipses as follows
Function Templates
A function templates work in similar manner as function but
with one key difference. A single function template can
work on different types at once but, different functions
are needed to perform identical task on different data
types.
If you need to perform identical operations on two or
more types of data then, you can use function
overloading. But better approach would be to use
function templates because you can perform this task by
writing less code and code is easier to maintain.
Class Template
Templates are a feature of the C++ programming language that allows
functions and classes to operate with generic types. This allows a function or
class to work on many different data types without being rewritten for each
one.
template <class T> class class-name
{
.....
//class member specification
};
The class template is very similar to an ordinary class definition except the
prefix template
<class T> and use of type T.The prefix tells the compiler that we are going to
declare a template and use T as a type name in the declaration.T may be
substituted by any data type including the user defined types.
STANDARD TEMPLATE LIBRARY
 Most computer programs exist to process data. The
data may represent a wide variety of realworld
information: personnel records, inventories, text
documents, the results of scientific experiments, and so
on.
 Whatever it represents, data is stored in memory and
manipulated in similar ways. University computer science
programs typically include a course called
“DataStructures and Algorithms.” The term data
structures refers to the ways data is stored in
memory,and algorithms refers to how it is manipulated.
STANDARD TEMPLATE LIBRARY
 C++ classes provide an excellent mechanism for
creating a library of data structures. In the past,
compiler vendors and many third-party developers
offered libraries of container classes to handle the
storage and processing of data. However, Standard
C++ includes its own builtin container class library.
It’s called the Standard Template Library (STL), and
was developed by Alexander Stepanov and Meng
Lee of Hewlett Packard. The STL is part of the
Standard C++ class library, and can be used as a
standard approach to storing and processing data
Components of STL:
Components of STL:
 The STL contains several kinds of entities. The three most
important are containers, algorithms,and iterators.
 A container is a way that stored data is organized in
memory. There are two kinds of containers: stacks and
linked lists. Another container, the array, is socommon
that it’s built into C++ (and most other computer
languages). However, there are many other kinds of
containers, and the STL includes the most useful. The STL
containers are implemented by template classes, so they
can be easily customized to hold different kinds ofdata.
Components of STL:
 Algorithms in the STL are procedures that are
applied to containers to process their data in
variousways. For example, there are algorithms to sort,
copy, search, and merge data. Algorithms are
represented by template functions. These functions are
not member functions of the container classes. Rather,
they are standalone functions.
 Iterators are a generalization of the concept of
pointers: they point to elements in a container.we can
increment an iterator, as you can a pointer, so it points
in turn to each element in a container. Iterators are a
key part of the STL because they connect algorithms
with containers.
Containers
 The STL contains sequence containers and
associative containers. The Containers are objects
that store data
Sequence Containers:
 A sequence container stores a set of elements in
linear sequence.Each element is related to other
element by its position along the line.They all
expand themselves to allow insertion of element
and all of them support a number of operations on
them.
Sequence Containers:
A vector container behaves like an array, but can automatically grow as
required. It is random access and contiguously stored, and length is highly
flexible. vector is the preferred sequence container for most applications.
When in doubt as to what kind of sequence container to use, start by using
a vector!
 An array container has some of the strengths of vector, but the length is not
as flexible.
 A deque (double-ended queue) container allows for fast insertions and
deletions at the beginning and end of the container. It shares the random-
access and flexible-length advantages of vector, but is not contiguous.
 A list container is a doubly linked list that enables bidirectional access, fast
insertions, and fast deletions anywhere in the container, but you cannot
randomly access an element in the container.
 A forward_list container is a singly linked list—the forward-access version
of list.
Associative Containers
 In associative containers are designed to support direct acces to element using
keys.They are not sequential. The associative containers can be grouped into two
subsets: maps and sets.
 A map, sometimes referred to as a dictionary, consists of a key/value pair. The key
is used to order the sequence, and the value is associated with that key. For
example, a map might contain keys that represent every unique word in a text and
corresponding values that represent the number of times that each word
appears in the text. The unordered version of map is unordered_map.
 A set is just an ascending container of unique elements—the value is also the key.
The unordered version of set is unordered_set.
 Both map and set only allow one instance of a key or element to be inserted into
the container. If multiple instances of elements are required, use multimap or
multiset. The unordered versions are unordered_multimap and
unordered_multiset.
 Ordered maps and sets support bi-directional iterators, and their unordered
counterparts support forward iterators.
Derived containers:

 The STL provides three Derived containers


namely,stack,queue and priority_queue. These are
also knows as container adaptors.
 stack,queue and priority_queue can be created
from different sequence containers.The Derived
containers do not support iterators and therefore
we cannot use them for data
mainpulation.However, they support two member
functions pop() and push() for deleting and inserting.
Overview of Standard Algorithms
 Algorithms are functions that can be used generally
across a variety of containers for processing their
content.Although each container provides functions for
its basics operations,STL provides more than sixty
standared algorithms to support more extended or
complex operations.Standard algorithms also permit us
to work with two different types of continers at the
same time.STL algorithm are not member function or
frienfs of containers.They are standalone template
functions.
 To have access to STL algorithm <algorithm> must be
include in the program.
Overview of Standard Algorithms
 STL algorithm,based on the nature of the operations
they perform,they are categorised under
 Retrieve or non-mutating algorithm
 mutating algorithm
 Sorting algorithm
 Set algorithm
 Relational algorithm
Multiple Choice Question
Input or output devices that are connected to
computer are called ______________.

A. Input/Output Subsystem
B. Peripheral Devices
C. Interfaces
D. Interrupt
Answer :B
Multiple Choice Question
How many types of modes of I/O Data Transfer?

A. 2
B. 3
C. 4
D. 5

Answer: B
Multiple Choice Question
Keyboard and Mouse Comes under?

A. Input peripherals
B. Output peripherals
C. Input-Output peripherals
D. None of the above
Answer A
Multiple Choice Question
The method which offers higher speeds of I/O
transfers is ___________

A. Interrupts
B. Memory mapping
C. Program-controlled I/O
D. DMA

Answer: D
Multiple Choice Question
In memory-mapped I/O ____________

A. The I/O devices have a separate address space


B. The I/O devices and the memory share the same
address space
C. A part of the memory is specifically set aside for the
I/O operation
D. The memory and I/O devices have an associated
address space

Answer: B
Non modifying operations:
 for_each Do specified operation for each element in a sequence
 find Find the first occurence of a specified value in a sequence
 find_if Find the first match of a predicate in a sequence
 find_first_of Find the first occurence of a value from one sequence
in another adjacent_find Find the first occurence of an adjacent
pair of values
 countCount occurences of a value in a sequence
 count_if Count matches of a predicate in a sequence
 accumulate Accumulate (i.e., obtain the sum of) the elements of a
sequence equal Compare two ranges
 max_elementFind the highest element in a sequence
 min_element Find the lowest element in a sequence
Modifying operations:
 transform Apply an operation to each element in an input
sequence and store the result in an output sequence (possibly the
same input sequence)
 copy Copy a sequence
 replace Replace elements in a sequence with a specified value
 replace_if Replace elements matching a predicate
 remove Remove elements with a specified value
 remove_if Remove elements matching a predicate
 reverse Reverses a sequence
 random_shuffle Randomly reorganize elements using a uniform
distribution fill Fill a sequence with a given value
 generate Fill a sequence with the result of a given operation

Sorting:
 sort Sort elements
 stable_sort Sort maintaining the order of equal
elements nth_element Put nth element in its place
 binary_search Find a value in a sequence,
performing binary search
Numeric operations
Set operations (on sorted ranges)
Iterator:
 Iterators behaves like pointer and are used to acces
container elements.They are often used to traverse
from one element to another,a process known as
iterating through the container.
 Different types of iterator must used with thwe
different types of containers
 Each type of iterator is used for performing certain
functionsthe venn diagram of iterator is as follows
Iterator
Iterator
 The input and output iterator supports the least
functions. They can be used only to traverse in a
container.
 The forward iterator supports all operations of input
and output iterator and also retains its position in the
container.
 A bidirectional iterator support all forward iterator
operations, provides the ability to move in the
backward direction in the container.
 A random access iterator combines the functionality of
a bidirectional iterator with an ability to jump to an
arbitrary location.
Allocators
STL provides allocator that does all the memory
management of the container classes. The concept
of allocators was originally introduced to provide
an abstraction for different memory models to
handle the problem of having different pointer
types on certain 16-bit operating systems (such as
near, far, and so forth).
However, this approach failed. Nowadays, allocators
serve as an abstraction to translate the need to use
memory into a raw call for memory.
Allocators
 Allocators separate the implementation of
containers, which need to allocate memory
dynamically, from the details of the underlying
physical memory management.
 Thus, different memory models such as shared
memory, garbage collections, and so forth to your
containers without any hassle because allocators
provide a common interface
Allocators
 'T' represents the vector's value type—in other words,
the type of object that is stored in the vector. 'Alloc'
represents the vector's allocator, the method for the
internal memory management.
 The internal implementation of the allocator is
completely irrelevant to the vector itself. It is simply
relying on the standardized public interface every
allocator has to provide. The vector does not need to
care any longer whether it would need to call 'malloc',
'new', and so on to allocate some memory; it simply
calls a standardized function of the allocator object
named 'allocate()' that will simply return a pointer to
the newly allocated memory.
Multiple Choice Question
The ________ circuit is basically used to extend the
processor BUS to connect devices.

A. Router
B. Router
C. Bridge
D. None of the above
Answer: C
Multiple Choice Question
The ISA is an architectural standard developed by
______.

A. IBM
B. AT&T Labs
C. Microsoft
D. Oracle

Answer: A
Multiple Choice Question
The registers of the controller are ______

A. 16 bit
B. 32 bit
C. 64 bit
D. 128 bit
Answer: B
Multiple Choice Question
Which of the following is true about DMA?

A. DMA is an approach of performing data transfers in bulk between


memory and the external device without the intervention of the
processor.
B. The DMA controller acts as a processor for DMA transfers and
overlooks the entire process.
C. The DMA controller has 3 registers.
D. All of the above

Answer: D
Multiple Choice Question
The SCSI BUS is used to connect the video devices to a processor by
providing a ______________.

A. Single Bus
B. USB
C. SCSI
D. parallel BUS

Answer: D
UNIT 4
INHERITANCE
INHERITANCE
DEFINITION:
 The mechanism of deriving the new class from an

old one is called inheritance.


 The old class is called as base class and the new
class is called as derived class.
INHERITANCE
The mechanism of deriving a new class from an old one is
called inheritance(or derivation). The old class is
referred to as the base class and the new one is called
the derived class. The derived class with only one base
class is called single inheritance and one with several
base classes is called multiple inheritance.
On the other hand, the traits of one class may be
inherited by more than one class. This process is known
as hierarchical inheritance. The mechanism of deriving a
class from another ‘derived class’ is known as multilevel
inheritance.
Types of Inheritance
 Single inheritance
 Multiple inheritance
 Multilevel inheritance
 Hierarchical inheritance
 Hybrid inheritance
Types of Inheritance
Types of Inheritance
Types of Inheritance
Types of Inheritance
Types of Inheritance
Multiple Choice Question
Q)base class and derived class relationship comes
under
 Inheritance

 Polymorphism

 encapsulation

 None

Answer : A
Multiple Choice Question
Q) C++ Inheritance relationship is
 Association

 Is-A

 Has-A

 None

Answer: B
Multiple Choice Question
Q) Types of inheritance in C++ are
 Multilevel

 Multiple

 Hierarchical

 All the above

Answer: D
Multiple Choice Question
Q) Inheritance allow in C++ Program?
 Class Re-usability

 Creating a hierarchy of classes

 Extendibility

 All

Answer: D
Multiple Choice Question
Q) Functions that can be inherited from base class in
C++ program
 Constructor

 Destructor

 Static function

 None

Answer: D
Defining Derived Classes:-
A derived class is defined by specifying its relationship
with the base class in addition to its own details.
The general form:-
class derived-class-name: visibly-mode base-class-
name
{
------------//
------------//members of derived class
------------
};
SINGLE INHERITANCE

The new class can be derived from only one base


class is called single inheritance.
Let us consider a simple example to illustrate
inheritance. The following program shows the base
class B and a derived class D. The class B contains
one private data
member, one public data member, and three public
member functions. The class D contains one private
data member and two public member functions.
SINGLE INHERITANCE
A private member of a base class cannot be inherited
and therefore it is not available for derived class
directly. A protected which serve a limited purpose
in inheritance. A member declared as protected is
accessible by the member functions within its class
and any class immediately derived from it. It cannot
be accessed by the functions outside these two
classes. A class can now use all the three visibility
modes
Example
class alpha
{
private:
------- //optional
------- // visible to member functions
------- // within its class protected:
---------- // visible to member functions
---------- // of its own and derived class public:
---------- // visible to all functions
---------- //in the program
}
SINGLE INHERITANCE
When a protected member is inherited in public
mode, it becomes protected in the derived class too,
and therefore is accessible by the member functions
of the derived class. It is also ready for further
inheritance. A protected member, inherited in the
private mode derivation, becomes private in the
derived class. Although it is available to the
member functions of the derived class, it is not
available for further inheritance.
Multilevel Inheritance
Multilevel Inheritance
The class A serves as a base class for the derived class B which in turn serves as a base class for the derived class C. The chain ABC
is known as inheritance path.
A derived class with multilevel inheritance is declared as follows. class A(….) ;
class B:public A(…..); class C:public B(…..);
The multilevel inheritance is defined as, the new class is derived from another derived class.
Here the class A serves as a base class for the derived class B which in turn serves as a base class for the derived class C. The
derived class is defined as,
Class A
{
//body of base class A
};
Class B : public A
{
//body of intermediate base class B
};

Class C : public B
{
//body of derived class
};
Multilevel Inheritance
A class can inherit the attributes or properties of two
or more classes that is a new class can be derived
from more than one base class is called multiple
inheritance. Here the class A , class B and class C
serves as a base class for the derived class D
Multilevel Inheritance
The hierarchical inheritance structure is given below.
This type is helpful when we have class hierarchies.
In this scheme the base class will include all the
features that are common to the subclasses.
HYBRID INHERITANCE

 Hybrid inheritance = multiple inheritance + multi-


level inheritance
 The hybrid inheritance is defined as a combination
of multilevel and multiple inheritances. This new
class can be derived by either multilevel or multiple
method or both.
Multiple Choice Question
Q)____________ members of base class are
inaccessible to derived class
 Private

 Protected

 Public

 None

Answer: A
Multiple Choice Question
Q) Accessing functions from multiple classes to a
derived class is known as
 multiple inheritance

 single inheritance

 Hybrid inheritance

 multilevel inheritance

Answer:A
Multiple Choice Question
Q) In inheritance, order of execution of base class and
derived class destructors are
 Base to derived

 Derived to base

 Random order

 none

Answer: B
Multiple Choice Question
Which among the following best describes the
Inheritance?
a) Copying the code already written
b) Using the code already written once
c) Using already defined functions in programming
language
d) Using the data and functions into derived
segment
Answer: d
Multiple Choice Question
How many basic types of inheritance are provided as
OOP feature?
a) 4
b) 3
c) 2
d) 1

Answer: a
VIRTUAL FUNCTION
When we use the same function name in base and derived classes, the
function in the base classes is declared as virtual using keyword
‘virtual’ preceding its normal declaration.
The member function that can be changed at runtime is called virtual
function.
Class classname
{
public:
.....
virtual returntype functionname (arguments)
{
.....
. . . . .}};
VIRTUAL FUNCTION
 The virtual function should be defined in the public
section of a class. When one function is made virtual
and another one is normal, and compiler determines
which function to call at runtime. In this we have to
create a ‘base pointer’.
 If the base pointer paints to a base class object
means it will execute the base class function.
 If the base pointer points to a derived class object
means it will execute the derived class function.
VIRTUAL FUNCTION
The base pointer first holds the address of the base
class object means it will run the base class member
function display and show will be executed. Next
the base pointer points to the derived class object,
in this before executing the derived class function if
will check whether the corresponding base class
function is ‘virtual’ or not, if it is not virtual then
execute the base class function otherwise it will
execute the derived class function.
Rules for virtual function
 Virtual function must be a members of some class.
 They cannot be static members.
 They are accessed by using base pointer.
 A virtual function in a base class must be defined
eventhough it may not be used.
 A prototype (or declaration) of a base class virtual function
and all the derived class version must be identical.
 We cannot we a pointer to a derived class to access an
object of the base class.

VIRTUAL BASE CLASS
The duplication of inherited members due to the multiple paths can be avoided by making the common base class as virtual base class while declaring the direct or intermediate base classes as
shown below.

class A

------

-----

};

class B1:virtual public A

-----

-----

};

class B2:public virtual A

-----

-----

};

class C:public B1,public B2

-----

-----

};
Abstract classes Pure Virtual
functions
 The virtual function doesn’t have any operation is
called “do-nothing” function or pure virtual function.
 This is represented as
 virtual void display()=0;
 Such functions are called pure functions. This pure
virtual class is also called abstract base class.
Multiple Choice Question
Which among the following best defines single level
inheritance?
a) A class inheriting a derived class
b) A class inheriting a base class
c) A class inheriting a nested class
d) A class which gets inherited by 2 classes

Answer: a
Multiple Choice Question
Which programming language doesn’t support
multiple inheritance?
a) C++ and Java
b) C and C++
c) Java and SmallTalk
d) Java

Answer: d
Multiple Choice Question
Which among the following is correct for a hierarchical
inheritance?
a) Two base classes can be used to be derived into one
single class
b) Two or more classes can be derived into one class
c) One base class can be derived into other two
derived classes or more
d) One base class can be derived into only 2 classes
Answer: c
Multiple Choice Question
 Which is the correct syntax of inheritance?
a) class derived_classname : base_classname{
/*define class body*/ };
b) class base_classname : derived_classname{
/*define class body*/ };
c) class derived_classname : access
base_classname{ /*define class body*/ };
d) class base_classname :access derived_classname{
/*define class body*/ };
Answer: c
Multiple Choice Question
Which type of inheritance leads to diamond problem?
a) Single level
b) Multi-level
c) Multiple
d) Hierarchical

Answer: c
Multiple Choice Question
Which access type data gets derived as private
member in derived class?
a) Private
b) Public
c) Protected
d) Protected and Private

Answer: a
Multiple Choice Question
If a base class is inherited in protected access mode then
which among the following is true?
a) Public and Protected members of base class becomes
protected members of derived class
b) Only protected members become protected
members of derived class
c) Private, Protected and Public all members of base,
become private of derived class
d) Only private members of base, become private of
derived class
Answer: a
Multiple Choice Question
Members which are not intended to be inherited are
declared as ________________
a) Public members
b) Protected members
c) Private members
d) Private or Protected members

Answer :c
Multiple Choice Question
While inheriting a class, if no access mode is
specified, then which among the following is true?
(in C++)
a) It gets inherited publicly by default
b) It gets inherited protected by default
c) It gets inherited privately by default
d) It is not possible
Answer: c
Multiple Choice Question
If a derived class object is created, which constructor
is called first?
a) Base class constructor
b) Derived class constructor
c) Depends on how we call the object
d) Not possible

Answer: a
Multiple Choice Question
How can you make the private members inheritable?
a) By making their visibility mode as public only
b) By making their visibility mode as protected only
c) By making their visibility mode as private in
derived class
d) It can be done both by making the visibility mode
public or protected

Answer: d
Multiple Choice Question
When a class serves as base class for many derived
classes, the situation is called:
 polymorphism

 hierarchical inheritance
 hybrid inheritance

 multipath inheritance

Answer: hierarchical inheritance


Multiple Choice Question
When two or more classes serve as base class for a
derived class, the situation is known as __________
 multiple inheritance

 polymorphism

 encapsulation

 hierarchical inheritance

Answer: multiple inheritance


Multiple Choice Question
Multiple inheritance leaves room for a derived class to
have _______ members
 dynamic

 private

 public

 ambiguous

Answer: ambiguous

You might also like