Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: oops concept
Description: easily to understand and learn concept of all topics
Description: easily to understand and learn concept of all topics
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
Subject: Object Oriented Programming
through C++
Unit-I
Introduction
Object oriented Programming
Object oriented Programming is defined as an approach that provides a way of modularizing
programs by creating partitioned memory area for both data and functions that can be used as
templates for creating copies of such modules on demand
...
After being created, classes can be reused over and over
again to develop new programs
...
Basic Concepts of Object oriented Programming
1
...
A class is a logical abstraction
...
A class specifies both code and data
...
When you define a class, you
declare the data that it contains and the code that operates on that data
...
The code and data that constitute a class are called members of the class
...
Object
An object is an identifiable entity with specific characteristics and behavior
...
Defining an object is similar to defining a variable of any data type
...
3
...
C++’s basic unit of encapsulation is the
class
...
Private code or data
is known to and accessible by only another part of the object
...
When code or data is public, other
parts of your program can access it even though it is defined within an object
...
This
insulation of the data from direct access by the program is called data hiding
...
Data abstraction
In object oriented programming, each object will have external interfaces through which it can be
made use of
...
The object itself may be made of many
smaller objects again with proper interfaces
...
The internal details of the objects are hidden which makes them abstract
...
5
...
It allows a
hierarchy of classes to be build, moving from the most general to the most specific
...
The inheriting class is called
the derived class
...
The
base class defines all qualities that will be common to any derived class
...
In essence, the base class represent the most general
description of a set of traits
...
6
...
The specific action is determined by the exact nature of the
situation
...
” This means that it is possible to design a generic interface to a group of related activities
...
It is the compiler’s job to select the specific action as it applies to each situation
...
In C++, it is possible to use one function name for many different purposes
...
Polymorphism can also be applied to operators
...
In run time polymorphism, the compiler selects the appropriate function for a particular call while the
program is running
...
Need for Object oriented Programming
Object-oriented programming scales very well, from the most trivial of problems to the most complex
tasks
...
Object-oriented programming was developed because limitations were discovered in earlier
approaches to programming
...
First, functions have unrestricted
access to global data
...
Benefits of Object oriented Programming
1
...
2
...
3
...
Changes inside a class do not affect any other part of a program, since the only public
interface that the external world has to a class is through the use of methods
...
Extensibility: adding new features or responding to changing operating environments can be
solved by introducing a few new objects and modifying some existing ones
...
Maintainability: objects can be maintained separately, making locating and fixing problems easier
...
Re-usability: objects can be reused in different programs
...
It was developed by Bjarne Stroustrup in 1979 at
Bell Laboratories in Murray Hill, New Jersey
...
"
However, in 1983 the name was changed to C++
...
Stroustrup built C++ on the foundation of C, including all of C’s features,
attributes, and benefits
...
These features comprise of classes, inheritance, function overloading
and operator overloading
...
C++ is used for developing applications such as editors, databases, personal file systems, networking
utilities, and communication programs
...
A Simple C++ Program
#include
h>
int main()
{
cout<< “Simple C++ program without using class”;
return 0;
}
Lines beginning with a hash sign (#) are directives read and interpreted by what is known as
the preprocessor
...
In this case, the directive #include
The function named main is a special function in all C++ programs; it is the function called when the
program is run
...
The open brace ({) indicates the beginning of main's function definition, and the closing brace (})
indicates its end
...
The identifier cout (pronounced as
c out) denotes an object
...
The
operator << is called insertion operator
...
The program ends with this statement:
return 0;
This causes zero to be returned to the calling process (which is usually the operating system)
...
Abnormal program termination should
be signaled by returning a nonzero value
...
Documentation Section
2
...
Global Declaration Section
4
...
Main C++ program function called main ( )
C++ keywords
When a language is defined, one has to design a set of instructions to be used for communicating with
the computer to carry out specific operations
...
These are also known as reserved words of the language
...
These words cannot be used for any other purpose, such as naming a variable
...
C++ keywords are:
Identifiers
An identifier is a name assigned to a function, variable, or any other user-defined item
...
Rules for naming identifiers:
Variable names can start with any letter of the alphabet or an underscore
...
Uppercase and lowercase are distinct
...
Data types
Data type defines size and type of values that a variable can store along with the set of operations that
can be performed on that variable
...
There are the seven basic data types in C++ as
shown below:
Type
char(character)
wchar_t(Wide character)
Meaning
holds 8-bit ASCII characters
holds characters that are part of large character sets
int(Integer)
represent integer numbers having no fractional part
float(floating point)
stores real numbers in the range of about 3
...
4x10 38,with a precision of seven digits
...
7x10
–308 to1
...
bool(Boolean)
can have only two possible values: true and false
...
A modifier alters the
meaning of the base type so that it more precisely fits the needs of various situations
...
Variables are
run time entities
...
When a
variable is given a value, that value is actually placed in the memory space assigned to the variable
...
The general form of a declaration is:
type variable_list;
Here, type must be a valid data type plus any modifiers, and variable_list may consist of one or more
identifier names separated by commas
...
Constants can be of any of the basic data
types
...
Constants are also called literals
...
g,
const int LENGTH = 10;
Enumerated Types
An enumerated type declares an optional type name and a set of zero or more identifiers that can be
used as values of the type
...
Creating an
enumeration requires the use of the keyword enum
...
The list of names is comma separated
...
Finally, c is assigned the value "blue"
...
But you can give a name, a specific value by adding an initializer
...
enum color { red, green=5, blue };
Here, blue will have a value of 6 because each name will be one greater than the one that precedes it
...
C++ is rich in built-in operators
...
Arithmetical operators
Arithmetical operators +, -, *, /, and % are used to performs an arithmetic (numeric) operation
...
Modulus or
remainder % operator is used only with the integral data type
...
All relational operators are
binary operators and therefore require two operands
...
The following table shows the relational operators
...
The logical operators are
Operators
||
&&
!
Meaning
OR
AND
NOT
Assignment operator
The assignment operator '=' is used for assigning a variable to a value
...
For example:
m = 5;
The operator takes the expression on the right, 5, and stores it in the variable on the left, m
...
In addition to standard
assignment operator shown above, C++ also support compound assignment operators
...
The increment/decrement operator can be used with any type of variable but it cannot
be used with any constant
...
The syntax of the increment operator is:
Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: ––variable
Post-decrement: variable––
In Prefix form first variable is first incremented/decremented, then evaluated
In Postfix form first variable is first evaluated, then incremented / decremented
...
The format of the
conditional operator is :
Conditional_ expression ? expression1 : expression2;
If the value of conditional expression is true then the expression1 is evaluated, otherwise expression2
is evaluated
...
The comma operator
The comma operator gives left to right evaluation of expressions
...
int a = 1, b = 2, c = 3, i; // comma acts as separator, not as an operator
i = (a, b); // stores b into i would first assign the value of a to i, and then assign value of b to variable i
...
The sizeof operator
The sizeof operator can be used to find how many bytes are required for an object to store in memory
...
For example, you
might have a float that you need to use in a function that requires an integer
...
It automatically converts
one type into another type
...
For
example this warning: conversion from ‘double’ to ‘int’, possible loss of data
...
With control we mean, you did not decide to convert to another type, the compiler did
...
Explicit conversion
The C++ language have ways to give you back control
...
Four typecast operators
The C++ language has four typecast operators:
static_cast
reinterpret_cast
const_cast
dynamic_cast
Type Conversion
The Type Conversion is that which automatically converts the one data type into another but
remember we can store a large data type into the other
...
When a user can convert the one data type into then it is called as the type casting
...
When we use the Type Conversion then it is called the
promotion
...
When we use the type casting then we can loss some data
...
C++ supports two types of selection statements :if
and switch
...
If Statement:
The syntax of an if statement in C++ is:
if(condition)
{
// statement(s) will execute if the condition is true
}
If the condition evaluates to true, then the block of code inside the if statement will be executed
...
Flowchart showing working of if statement
// A Program to find whether a given number is even or odd using if … else statement
#include
h>
int main()
{ int n;
cout<<”enter number”;
cin>>n;
if(n%2==0)
cout<<”Even number”;
else
cout<<”Odd number”;
return 0;
}
The if
...
Flowchart
if
...
else Statement
An if statement can be followed by an optional else if
...
else if statement
...
}
Nested if Statement
It is always legal to nest if-else statements, which means you can use one if or
else if statement inside another if or else if statement(s)
...
When a match is found, the
statements associated with that constant are executed
...
...
Floating-point expressions, for example,
are not allowed
...
When a match is found, the statement sequence associated with that
case is executed until the break statement or the end of the switch statement is reached
...
The default is optional and, if it is not present, no
action takes place if all matches fail
...
You can use it in loops as well as in the switch
statement
...
Flowchart
2) Loop control structures
A loop statement allows us to execute a statement or group of statements multiple times
...
C++ provides three convenient iterative statements: while, for, and do-while
...
It is
an entry-controlled loop
...
The condition may be any
expression, and true is any non-zero value
...
After each
execution of the loop, the value of test expression is changed
...
Flowchart
// A program to display numbers from 1 to 100
#include
h>
int main(){
int i=1;
while(i<=100){
cout<i++;
}
return 0;
}
The do-while Loop
The do-while loop differs from the while loop in that the condition is tested after the body of the loop
...
It is an exit-controlled loop
...
If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop execute again
...
// A program to display numbers from 1 to 100
#include
h>
int main( ){
int i=1;
do
{
cout<i++;
} while(i<=100);
return 0;
}
for Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times
...
The init step is executed first, and only once
...
You are not required to put a statement here, as long as a semicolon appears
...
Next, the condition is evaluated
...
If it is false, the body
of the loop does not execute and flow of control jumps to the next statement just after the for loop
...
After the body of the for loop executes, the flow of control jumps back up to the increment
statement
...
This statement can be
left blank, as long as a semicolon appears after the condition
...
The condition is now evaluated again
...
After the condition becomes false, the
for loop terminates
...
h>
#include
This unit can then
be invoked from other parts of the program
...
Functions help to reduce the program size when same set of instructions are to be executed again and
again
...
Function declaration — prototype:
A function has to be declared before using it, in a manner similar to variables and constants
...
The general form of a C++ function declaration is as follows:
return_type function_name( parameter list );
Function definition
The function definition is the actual body of the function
...
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{ body of the function }
Here, Return Type: A function may return a value
...
Some functions perform the desired operations without returning a value
...
Function Name: This is the actual name of the function
...
When a function is invoked, you pass a value to the
parameter
...
The parameter list refers to the
type, order, and number of the parameters of a function
...
Function Body: The function body contains a collection of statements that define what the function
does
...
To call a function, you simply need to
pass the required parameters along with function name, and if function returns a value, then you can
store returned value
...
h>
#include
The reason that inline functions are an important addition to C++ is that they
allow you to create very efficient code
...
Typically, arguments are pushed onto the
stack and various registers are saved when a function is called, and then restored when the function
returns
...
However, when a function is expanded inline,
none of those operations occur
...
For this reason, it is best to
inline only very small functions
...
The
compiler can choose to ignore it
...
If a
function cannot be inlined, it will simply be called as a normal function
...
h>
#include
They can be used almost
anywhere in your code because they are replaced with their expansions before any compilation starts
...
They can only
be used where a function call is appropriate
...
As a result, there are several important differences:
Inline functions follow all the protocols of type safety enforced on normal functions
...
Expressions passed as arguments to inline functions are evaluated once
...
macros are expanded at pre-compile time, you cannot use them for debugging, but you can
use inline functions
...
Once a
reference is initialized with a variable, either the variable name or the reference name may be used to
refer to the variable
...
The syntax for declaring a reference variable is:
datatype &Ref = variable name;
Example:
int main(){
int var1=10;
//declaring simple variable
int & var2=var1; //declaring reference variable
cout<<“\n value of var2 =” << var2;
return 0;
}
var2 is a reference variable to var1
...
This code prints the value
of var2 exactly as that of var1
...
When using call-by-value, a copy of the argument is passed to the function
...
By default, C++ uses call-by-value
...
When we pass arguments by reference, the formal arguments in the called function become aliases to
the actual arguments in the calling function
...
Example
#include
h>
void swap(int &x, int &y); // function declaration
int main (){
int a = 10, b=20;
cout << "Before swapping”<
swap(a, b);
//calling a function to swap the values
...
int temp;
temp = x;
x = y;
y = temp;
}
Output:
Before swapping
value of a:10 value of b:20
After swapping
value of a:20 value of b:10
Function Overloading
Function overloading is the process of using the same name for two or more functions
...
It is only through these differences that the compiler knows which function to call in any
given situation
...
To overload a function, simply declare and
define all required versions
...
Two functions differing only in their
return types cannot be overloaded
...
h>
#include
5);
//calls func2
cout<<”sum=”<< sum(13
...
5);
//calls func3
return 0;
}
int sum(int p,int q,int r){
//func1
return(a+b+c);
}
double sum(int l,double m){
//func2
return(l+m);
}
float sum(float p,float q){
//func3
return(p+q);
}
Default arguments
C++ allows a function to assign a parameter a default value when no argument corresponding to that
parameter is specified in a call to that function
...
All default parameters must be to the right of any
parameters that don't have defaults
...
When you create a function that has one or more default arguments, those
arguments must be specified only once: either in the function's prototype or in the function's definition
if the definition precedes the function's first use
...
They are also useful in cases where, after a program is
written, the programmer decides to increase the capability of a function by adding another argument
...
Example
#include
h>
int sum(int a, int b=20){
return( a + b);
}
int main (){
int a = 100, b=200, result;
result = sum(a, b);
//here a=100 , b=200
cout << "Total value is :" << result << endl;
result = sum(a);
//here a=100 , b=20(using default value)
cout << "Total value is :" << result << endl;
return 0;
}
Unit-III
Class
A class is a user defined data type
...
It is a template that defines the
form of an object
...
It is not until an object of that class has been
created that a physical representation of that class exists in memory
...
Data is contained in instance
variables defined by the class known as data members, and code is contained in functions known as
member functions
...
The
general form of class declaration is:
class class-name {
access-specifier:
data and functions
access-specifier:
data and functions
//
...
If present, it declares objects of the class
...
The public access_specifier allows functions or data to be
accessible to other parts of your program
...
Example:
#include
h>
Class myclass {
// class declaration
// private members to myclass
int a;
public:
// public members to myclass
void set_a(intnum);
int get_a( );
};
Object
An object is an identifiable entity with specific characteristics and behavior
...
Defining an object is similar to defining a variable of any data type: Space is set
aside for it in memory
...
This is also called
instantiating them
...
program code
}
Accessing Class Members
The main() cannot contain statements that access class members directly
...
To access class members, use the dot (
...
The dot
operator links the name of an object with the name of a member
...
member
Example
ob1
...
A member function can call another member
function directly, without using the dot operator
...
h>
#include
sum();
getch();
return(0);
}
Scope Resolution operator
Member functions can be defined within the class definition or separately using scope resolution
operator (::)
...
Defining a member function using scope resolution operator uses
following declaration
return-type class-name::func-name(parameter- list) {
// body of function
}
Here the class-name is the name of the class to which the function belongs
...
That is,
the scope of the function is restricted to the class-name specified
...
In many
situation, it happens that the name of global variable and the name of the local variable are same
...
If we want
to access or use the global variable, then the scope resolution operator (::) is used
...
Unlike
regular data members, individual copies of a static member variable are not made for each object
...
Thus, all
objects of that class use that same variable
...
When you declare a static data member within a class, you are not defining it
...
) Instead, you must provide a global definition for it elsewhere,
outside the class
...
This causes storage for the variable to be allocated
...
Another interesting use of a static member variable is to keep track of the
number of objects of a particular class type that are in existence
...
They may only directly refer to other static
members of the class
...
A static
member function can be called using the class name instead of its objects as follows:
class name :: function name
//Program showing working of static class members
#include
h>
class static_type {
static int i;
//static data member
public:
static void init(int x) {i = x;}
//static member function
void show() {cout << i;}};
int static_type :: i;
// static data member definition
int main(){
static_type::init(100);
static_type x;
x
...
It is
special because its name is same as the class name
...
It is called constructor because it construct the value data members of
the class
...
They should be declared in the public section
...
They do not have return types, not even void and therefore, they cannot return values
...
Example:
#include< iostream
...
h>
class myclass {
// class declaration
int a;
public:
myclass( );
//default constructor
void show( );
};
myclass :: myclass( ) {
cout <<"In constructor\n";
a=10;
}
myclass :: show( ) {
cout<< a;
}
int main( ) {
int ob; // automatic call to constructor
ob
...
Default constructor
The default constructor for any class is the constructor with no arguments
...
It
can be zero or any other value
...
Above program uses default constructor
...
Parameterized Constructor
It is possible to pass arguments to constructors
...
To create a parameterized constructor, simply add parameters to it the way you
would to any other function
...
#include
h>
class myclass {
int a, b;
public:
myclass(int i, int j) //parameterized constructor
{a=i; b=j;}
void show() { cout << a << " " << b;}
};
int main() {
myclass ob(3, 5); //call to constructor
ob
...
A constructor is said to be overloaded when the same
constructor with different number of argument and types of arguments initializes an object
...
If class definition does not explicitly include copy
constructor, then the system automatically creates one by default
...
Copy an object to pass it as an argument to a function
...
The most common form of copy constructor is shown here:
classname (const classname &obj) {
// body of constructor
}
Here, obj is a reference to an object that is being used to initialize another object
...
Destructor
A destructor destroys an object after it is no longer in use
...
But it will be preceded by the character Tilde
(~)
...
Each class has exactly one destructor
...
It will be invoked implicitly by the compiler upon exit from the program to clean up storage
that is no longer accessible
...
h>
#include
” ;
}
int main(){
Myclass ob1, ob2;
cout<
x;
return 0; }
Output:
10 10
Destructing……
...
Friend function
In general, only other members of a class have access to the private members of the class
...
To make a function a friend of a class, you include its prototype in the class
declaration and precede it with the friend keyword
...
But
while defining friend function, it does not use either keyword friend or :: operator
...
Member function of one class can be friend functions of another class
...
A friend, function has following characteristics
...
A friend function cannot be called using the object of that class
...
It cannot access the member variables directly & has to use an object name dot membership
operator with member name
...
Usually, it has the object as arguments
...
h>
#include
x<
getdata();
display(a);
getch();
return 0;
}
Operator overloading
There is another useful methodology in C++ called operator overloading
...
As the name
suggests, here the conventional operators can be programmed to carry out more complex operations
...
e
...
Such operators have to be specifically defined and
appropriate function programmed
...
It is simply that a new operation, relative to a specific class, is defined
...
A class that implements a
stack might use the + to push an object onto the stack
...
An operator function is created using the keyword operator
...
Operator functions can be either members or nonmembers of a
class
...
These operators cannot be overloaded:-
...
Declare the operator function operator op() in the public part of the class
...
Overloading a unary operator using member function
Overloading a unary operator using a member function, the function takes no parameters
...
There is no need
for another parameter
...
h>
#include
getdata(2,3,4);
a
...
display();
getch();
return 0;
}
Overloading binary operator
When a member operator function overloads a binary operator, the function will have only one
parameter
...
The object
on the left side is the object that generates the call to the operator function and is passed implicitly by
this pointer
...
#include
h>
class A{
int x,y;
public:
void input() {
cin>>x>>y;
}
void display() {
cout<<"\nx="<
A operator+(A p );
};
//overload binary + operator
A A :: operator+(A p) {
A t;
t
...
x;
t
...
y;
return t;
}
int main(){
A a1, a2, a3;
a1
...
input();
a3=a2+a1;
//activates operator+() function
a3
...
‘this’ is a C++ keyword
...
We can say that ‘this’
is a pointer
...
While overloading binary
operators, we use two objects, one that called the operator function and the other, which is passed to
the function
...
However, the
data member of the other object had a prefix
...
Inheritance
Inheritance is the mechanism by which one class can inherit the properties of another
...
When one class is
inherited by another, the class that is inherited is called the base class
...
In general, the process of inheritance begins with the definition of a base class
...
In essence, the base class
represent the most general description of a set of traits
...
When one class inherits another, it uses this general
form:
class derived-class-name : access base-class-name{
//
...
The access specifier
determines how elements of the base class are inherited by the derived class
...
If the access specifier is private, all public members of
the base class become private members of the derived class
...
It is important to understand that if the access specifier is private, public members of the base
become private members of the derived class
...
The protected access specifier is equivalent to the private specifier with the sole exception that
protected members of a base class are accessible to members of any class derived from that base
...
When a protected member
of a base class is inherited as public by the derived class, it becomes a protected member of the
derived class
...
A base class can also be inherited as protected by a derived class
...
Program to illustrate concept of inheritance
#include
h>
class base
//base class
{
int x,y;
public:
void show() {
cout<<"In base class";
}
};
class derived : public base
//derived class
{
int a,b;
public:
void show2() {
cout<<"\nIn derived class";
}
};
int main() {
derived d;
d
...
show2();
//uses derived class’s show2() function
getch();
return 0;
}
Types of Inheritances
Single Inheritance
The process in which a derived class inherits traits from only one base class, is called single
inheritance
...
The derived class
inherits the behavior and attributes of the base class
...
The derived
class can add its own properties i
...
data members (variables) and functions
...
We declare the base class and
derived class as given below:
class base_class {
};
class derived_ class : visibility-mode base_ class {
};
Program to illustrate concept of single inheritance
#include
h>
class base
//base class
{
int x,y;
public:
void show() {
cout<<"In base class";
}
};
class derived : public base //derived class
{
int a,b;
public:
void show2() {
cout<<"\nIn derived class";
}
};
int main() {
derived d;
d
...
show2();
//uses derived class’s show2() function
getch();
return 0;
}
Ambiguity in single Inheritance
Whenever a data member and member functions are defined with the same name in both the base and
derived class, ambiguity occurs
...
class name :: class member
Multiple Inheritance
The process in which a derived class inherits traits from several base classes, is called multiple
inheritance
...
We
declare the base classes and derived class as given below:
class base_class1{
};
class base_class2{
};
class derived_ class : visibility-mode base_ class1 , visibility-mode base_ class2 {
};
Multilevel Inheritance
The process in which a derived class inherits traits from another derived class, is called Multilevel
Inheritance
...
Hierarchical Inheritance
The process in which traits of one class can be inherited by more than one class is known as
Hierarchical inheritance
...
A derived class can serve as a base class for lower level classes and so on
...
Overriding
Overriding is defined as the ability to change the definition of an inherited method or attribute in a
derived class
...
When the signatures are the same, they are called function overriding
...
The implementation in the derived class overrides or replaces the
implementation in the corresponding base class
...
To
understand what this problem is, consider the following class hierarchy:
Here the base class Base is inherited by both Derived1and Derived2
...
However, this implies that Base is actually inherited twice by Derived3
...
This causes ambiguity when a
member of Base is used by Derived3
...
This feature is called a virtual base class
...
Doing this prevents two or more copies of
the base from being present in any subsequent derived class that inherits the base class indirectly
...
// This program uses a virtual base class
...
// However, only one copy of base is inherited
...
i = 10; // unambiguous because virtual Base
ob
...
k = 5;
cout << "Product is: " << ob
...
i=10 would have been
ambiguous and a compile-time error would have resulted
...
For example, assuming the preceding program, this fragment is perfectly valid:
Derived1 ob;
ob
...
When this is the case, the friend class and all
of its member functions have access to the private members defined within the other class
...
#include
h>
class A{
int x, y;
public:
friend void display(A &obj);
friend class B;
void getdata() {
cin>>x>>y;
}
};
class B{
int p,q;
public:
void get(A &obj) {
p=obj
...
y;
}
};
void display(A &obj){
cout<
y;
}
int main(){
A a;
B b;
b
...
It does not inherit the other class
...
Unit-IV
Pointer
A pointer is a variable that contains a memory address
...
For example, if x contains the address of y, then x is said to “point
to” y
...
The general form of a pointer variable declaration is
type *var-name;
Here, type is the pointer’s base type
...
var-name is the name of the pointer variable
...
Assign the address of a variable to a pointer
...
This is done by using
unary operator * that returns the value of the variable located at the address specified by its
operand
...
However, it is also possible
to access a member of an object via a pointer to that object
...
We can declare an object pointer just as a
pointer to any other type of variable is declared
...
To obtain the address of an object, precede the object with the & operator, just
as you do when taking the address of any other type of variable
...
h>
class myclass {
int a;
public:
myclass(int x); //constructor
int get( );
};
myclass :: myclass(int x) {
a=x;
}
int myclass :: get( ) {
return a;
}
int main( ) {
myclass ob(120); //create object
myclass *p; //create pointer to object
p=&ob; //put address of ob into p
cout <<"value using object: " <
It is
important to understand that creation of an object pointer does not create an object
...
The address of ob is put into p by using the statement:
p=&ob;
Finally, the program shows how the members of an object can be accessed through a pointer
...
In
general, a pointer of one type cannot point to an object of another type
...
In C++, a base class pointer can also be used to
point to an object of any class derived from that base
...
Any pointer declared as a pointer to B can also
be used to point to an object of type D
...
Thus, in this example, p can be used to access all elements of D_ob inherited from B_ob
...
Another point to understand is that although a base pointer can be used to point to a derived object,
the reverse is not true
...
C++ Virtual Function
A virtual function is a member function that is declared within a base class and redefined by a derived
class
...
When a class containing a virtual function is inherited, the derived class redefines the
virtual function relative to the derived class
...
Each redefinition of the virtual function by a derived class
implements its operation as it relates specifically to the derived class
...
When a virtual function is redefined by a derived class, the keyword virtual is not
needed
...
However, what makes a
virtual function interesting, and capable of supporting run-time polymorphism, is what happens when
a virtual function is called through a pointer
...
And this determination is made at run time
...
// A simple example using a virtual function
...
h>
#include
This situation is common because often a base class does not define a complete class by
itself
...
When there is no meaningful action for a base class virtual function to
perform, the implication is that any derived class must override this function
...
A pure virtual function has no definition relative to the
base class
...
To make a pure virtual function, use this general
form:
virtual type func-name(parameter-list) = 0;
The key part of this declaration is the setting of the function equal to 0
...
When a virtual function is made pure, it forces
any derived class to override it
...
Thus,
making a virtual function pure is a way to guaranty that a derived class will provide its own
redefinition
...
Since, an
abstract class contains atleast one function for which no body exists, it is, technically, an incomplete
type, and no objects of that class can be created
...
It is
important to understand, however, that you can still create a pointer to an abstract class, since it is
through the use of base class pointers that run-time polymorphism is achieved
...
C++ Streams
The C++ I/O system operates through streams
...
A stream is linked to a physical device by the C++ I/O system
...
Because all
streams act the same, the I/O system presents the programmer with a consistent interface
...
Input stream: a stream that extracts (reads) data from the source and sends it to the program
...
In formatted or high-level IO, bytes
are grouped and converted to types such as int, double, string or user-defined types
...
Formatted IO operations are supported
via overloading the stream insertion (<<) and stream extraction (>>) operators, which presents a
consistent public IO interface
...
Just as there are different
kinds of I/O (for example, input, output, and file access), there are different classes depending on the
type of I/O
...
It contains the overloaded extraction (>>) operator functions
...
Class ostream :- Defines output streams that can be used to write data
...
The ostream class contains the overloaded insertion (<<) operator function
When a C++ program begins, these four streams are automatically opened:
Stream
Meaning
Default Device
cin
Standard input
Keyboard
cout
Standard output
Screen
cerr
Standard error
Screen
clog
Buffer version of cerr
Screen
Cin and Cout objects
cout is an object of class ostream
...
Here, the standard output stream represents monitor
...
It inserts or sends
the contents of variable on its right to the object on its left
...
cin is a predefined object that corresponds to the standard input
stream
...
The >> operator is called the extraction
operator because it extracts data from a stream
...
For example:
int number;
cin >> number;
Here >> operator accepts value from keyboard and stores in variable number
...
There are two prototypes available in C++ for get as
given below:
get (char *)
get ()
Their usage will be clear from the example below:
char ch ;
cin
...
Let us now implement the get function using the other prototype:
char ch ;
ch = cin
...
The complement of get function for output is the put function of the ostream class
...
put (var);
Here the value of the variable var will be displayed in the console monitor
...
put (‘a’);
getline and write functions
C++ supports functions to read and write a line at one go
...
The end of the line is recognized by a new line character, which is generated by pressing the
Enter key
...
The prototype of the getline function is given below:
cin
...
The reading will stop when it encounters a new line character or when the required
number (size-1) of characters have been read, whichever occurs earlier
...
The Enter key or
Return key generates a new line character
...
Similarly, the write function displays a line of given size
...
Formatted I/O via manipulators
The C++ I/O system allows you to format I/O operations
...
I/O
manipulators are special I/O format functions that can occur within an I/O statement
...
File I/O and
console I/O are closely related
...
To perform file I/O, you must include
...
In C++, a file is opened by linking it to a
stream
...
Before you can open a file,
you must first obtain a stream
...
To create an output stream, declare an object of type ofstream
...
For example, this fragment creates one input stream, one output stream and one stream capable of
both input and output:
ifstream in; // input;
fstream out; // output;
fstream io;
// input and output
Once you have created a stream, one way to associate it with a file is by using the function open( )
...
The prototype for each is
shown here:
void ifstream::open(const char*filename,openmode mode=ios::in);
void ofstream::open(const char*filename,openmode mode=ios::out | ios::trunc);
void fstream::open(const char*filename,openmode mode=ios::in | ios::out);
Here filename is the name of the file, which can include a path specifier
...
It must be a value of type open mode, which is an enumeration
defined by ios that contains the following value:
• ios::app: causes all output to that file to be appended to the end
...
• ios::ate: causes a seek to the end of the file to occur when the file is opened
...
• ios::in: specify that the file is capable of input
...
By default, all files are opened in text
mode
...
However, when a file is opened in binary mode, no such
character translations will occur
...
When you create an output stream using ofstream, any pre-existing file is
automatically truncated
...
For example, if we want to open
the file example
...
open ("example
...
For that, we call the stream's
member function close
...
close();
Once this member function is called, the stream object can be re-used to open another file, and the file
is available again to be opened by other processes
...
To write to a file, you construct a ofsteam object connecting to the output file, and use
the ostream functions such as stream insertion <<, put() and write()
...
There are two ways of storing data in a file as given below:
Binary form and Text form
Suppose, we want to store a five digit number say 19876 in the text form, then it will be stored as five
characters
...
This requires storage of 40 bits
...
The savings will be
much more when we deal with floating point numbers
...
However, storing a
number in binary form requires storing it in bits
...
The
text format is easy to read
...
The portability of
text file is also assured
...
It also occupies lesser
space when we store it in binary form and hence it will be faster
...
Unformatted, binary I/O
C++ supports a wide range of unformatted file I/O functions
...
The lowest-level unformatted I/O functions are
get( )and put( )
...
These functions
are member functions of all input and output stream classes, respectively
...
Their prototypes are:
istream &read(char*buf, streamsize num);
ostream &write(const char*buf, streamsize num);
The read( ) function reads num bytes from the stream and puts them in the buffer pointed to by buf
...
The
streamsize type is some form of integer
...
If the end of file is reached before num
characters have been read, read( ) stops and the buffer contains as many characters as were available
...
The reason for this is easy to understand: specifying ios::binary prevents any
character translations from occurring
...
However, it is perfectly acceptable to use the
unformatted functions on a file opened in text mode, as long as that the file actually contains only
text
...
Random Access
File pointers
C++ also supports file pointers
...
The pointers are helpful in lower level operations in files
...
When we open a file for reading, we can use the get
pointer
...
When we open a file for writing, we can use put
pointer
...
When we open a file for reading, the
get pointer will be at location zero and not 1
...
Therefore,
automatically when we assign an object to ifstream and then initialize the object with a file name, the
get pointer will be ready to read the contents from 0 th position
...
Then, the put pointer will point to the 0 th position of the
given file name after it is created
...
But, when we say write, then the pointer will advance to one position after the last
character in the file
...
>
#include
int main(){
//Writing
ofstream outf;
outf
...
txt”);
outf<<“Working with files is fun\n”;
outf<<“Writing to files is also fun\n”;
outf
...
open(“Temp2
...
getline(buff, 80);
cout<
inf
Title: oops concept
Description: easily to understand and learn concept of all topics
Description: easily to understand and learn concept of all topics