Oops Notes
Oops Notes
Oops Notes
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.
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
8
Comparison
Program is divided into small parts Program is divided into small parts
called ‘Functions’ called ‘Objects’
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;
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.
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
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
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.
// 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; // declaration
i = 10; // initialization
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;
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 (!=).
30
Operators
• Logical Operators
31
Operators
• Bitwise operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are asfollows:
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
& 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
int a = 10;
a > 5 ? cout << "true" : cout << “false";
• 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
35
Library Functions
Table 2 Character Functions (cctype)
Function Meaning
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,
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.
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;
};
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;
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
46
Declaring, Defining and Calling Function
#include < iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling function
cout << c;
}
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);
} }
10 20
49
Call by reference
#include < iostream>
using namespace std;
int main()
{
int x = 10;
calc(&x); // passing address of x as argument
printf("%d", x);
}
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
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;
}
• 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.
int age[5];
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
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}
};
65
C- Strings
S.No Function & Purpose
67
C-Strings Example 2 #include <iostream>
#include <cstring>
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 ;
return 0;
}
68
#include <iostream>
String Class Example 3 #include <string>
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 :
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.
• 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.
• 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
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;
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
};
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);
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);
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
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
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; }
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
28
Binary Operator Overloading Example 1
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 :
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.
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.
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";
}
};
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();
}
};
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
{
.....
.....
};
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;
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
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++ 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.
int main ()
{
int *ptr = NULL;
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;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr[MAX];
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;
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;
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.
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 );
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();
};
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
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
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
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
};
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);
•
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
•
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
•
•
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
Types :
• Binary Operator Overloading
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
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)
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 ____________
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?
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
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
Answer: D
Multiple Choice Question
Q) Inheritance allow in C++ Program?
Class Re-usability
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
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
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
------
-----
};
-----
-----
};
-----
-----
};
-----
-----
};
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
polymorphism
encapsulation
hierarchical inheritance
private
public
ambiguous
Answer: ambiguous