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.
My Basket
computer memory£1.50
Embedded System Design and Software - Part 2£2.50
Total£4.00
Or: Edit My Basket
Title: C++
Description: A simple and easy note is here for u...I can bet u gonna pass any exam with this note...so guys what are you looking for??Download it and enjoy
Description: A simple and easy note is here for u...I can bet u gonna pass any exam with this note...so guys what are you looking for??Download it and enjoy
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
Chapter 1
Object Oriented Programming Approach
The term Object Oriented programming is frequently heard in the programming arena
...
It is popularly known by its acronym OOP
...
The programming technology is continuously developing since the start of the computer
and related technologies
...
Such enhancements increased complexity in programming
and design of large software
...
The software may need maintenance and
enhancements after the regular feedback from the users
...
While
improving the software work may need to begin from the scratch that may increase
software cost too
...
To overcome such problems software developers were
forced to develop new programming method
...
1
...
Since the beginning of the first
computer, programming for the computer started to develop software
...
itn
Page 1
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
1
...
1 Procedure Oriented Programming
In procedure oriented programming a large program is broken down into smaller
manageable parts called procedures or functions
...
In procedure oriented programming language, a program basically consists of sequence
of instructions each of which tells the computer to do something such as reading inputs
from the user, doing necessary calculation, displaying output
...
2 Basic of Object Oriented Programming
Objects are the entities that can be uniquely identified from others
...
In real world system everything exists in the form
of objects
...
Every object has two things, firstly its properties we call attributes and second its
behavior we call function
...
It has attributes like color,
number of seats, chassis number, engine number etc and behavior like move, stop,
accelerate, turn etc
...
Its sole objective is to overcome the limitation of Procedure Oriented
approach
...
larger, it is then broken into smaller units called procedure or functions
...
The primary focus of
procedural oriented programming is on functions rather than data
...
This technique is only suitable for medium sized software
applications
...
Data
within the function are called local data and the data which are not within any function
are called global data
...
So each function may access its local data as well as global data
...
If any data is to be accessed by two or more
functions it should be made global
...
Functions are action oriented and do not
correspond to the element of the problem
...
That’s why procedure oriented
programming approach does not model real world system perfectly
...
Characteristics of POP
The characteristics of procedure oriented programming are listed as follows:
A large program is broken down into small manageable procedures or functions
...
For sharing a common data among different functions the data is made global
...
The program design of procedure oriented programming follows top down
methodology
...
csitnepal
...
Focus on functions rather than data
...
The use of global data is error prone and it could be an obstacle in code
maintenance and enhancements
...
Maintaining and enhancing program code is still difficult because of global data
...
Since functions are action
oriented and do not really correspond to the elements of problem
...
In OOP, data are treated as a
critical element in the program and restricts freely transformation of data around the
system
...
OOP approach permits decomposition of a
problem into entities called objects and then build data and function around them
...
But function of
one object may access the function of another object
...
In OOP, an instance of such an entity
is known as object
...
Characteristics of OOPs
OOP is most sophisticated programming methodology among other methodologies by
far
...
Programs are divided into objects
...
Data can be hidden to prevent from accidental alteration from other function or
objects
...
Data structures are modeled as objects
...
Procedure oriented versus Object oriented programming
The differences between procedural and Object oriented programming are tabulated
below:
Object Oriented Programming
Emphasis is given on data
...
itn
Page 3
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Follow bottom-up approach of
program design
...
It does not model the real world It models the real world problem
ep
a
Procedure
Oriented
Programming
Emphasis is given on procedures
...
Follow top-down approach of
program design
...
problem perfectly
...
from
very well
...
Only related function can access
them
Maintaining and enhancing code is Maintaining and enhancing code is
still difficult
...
Code reusability is still difficult
...
Examples:
FORTRAN,COBOL, Example: C++, JAVA, Smalltalk
Pascal, C
Features of Object Oriented programming
Different features of object oriented programming are explained here
...
Object
Objects are the entities in an object oriented system through which we perceive the world
around us
...
The entities are then represented as objects in the
program
...
For example Automobiles are objects as they have size,
weight, color etc as attributes (that is data) and starting, pressing the brake, turning the
wheel, pressing accelerator pedal etc as operation (that is functions)
...
Following are some of the examples of objects in different scenario
...
csitnepal
...
2
...
Functions are used to
manipulate on the data
...
The class is the user defined data type used to declare
the objects
...
Once a class is defined, we can create any number of objects of its type
...
For example, manager, peon, secretary clerk are the objects of
the class employee
...
Classes are user defined data type (like a struct in C programming language) and behave
much like built in data type (like int, char, float) of programming language
...
Defining class doesn’t
create an object; however defining process specifies the data and function to be in the
objects of its type
...
Similarly, function Tot_marks () will sum the marks obtained by the
student
...
ep
a
itn
Page 5
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Each class describes a possibly infinite set of individual objects, each object is said
to be an instance of its class and each instance of the class has its own value for each
attribute but shares the attribute name and operations with other instances of the class
...
A class is an abstraction of the real world entities with similar properties
...
3
...
It focuses the outside view of an object, separating its
essential behavior from its implementation
...
Let’s take an example of vehicle
...
The abstraction allows the driver of the vehicle to
drive without having detail knowledge of the complexity of the parts
...
Similarly Operating System like Windows, UNIX provides abstraction to the user
...
Operating System
hides the truth about the disk hardware and presents a simple file-oriented interface
...
When data and it operation are presented together, the construct is call ADT
(Abstract Data Type)
...
For example, a student
class can be made and can be available to be used in programs
...
The program can use the function Sort_name() to sort the names in
alphabetical order without knowing whether the implementation uses bubble sort, merge
sort, quick sort algorithms
...
Encapsulation
The mechanism of wrapping up of data and function into a single unit is called
encapsulation
...
We can assume encapsulation as a protective wrapper that prevents the data
being accessed by other code defined outside the wrapper
...
The purpose of a class is to encapsulate complexity
...
The public interface of a class represents everything that
external users of the class may know about the data and function
...
The code other than
member of a class cannot access a private function or data
...
After hiding data by making them
private, it then safe from accidental alteration
...
csitnepal
...
Inheritance
Inheritance is the process by which objects of one class acquire the characteristics of
object of another class
...
This is possible by deriving a new class (derived class) from the existing
one (base class)
...
It provides the concept of hierarchical classification
...
We naturally view the
l
The public interface should be carefully designed no to expose too much of the inner
working of a class
...
Many objects are related to each other in a
hierarchical way, such as vehicle, four wheeler, and car
...
All vehicles have
common behavioral aspect like; they move, accelerate, turn and stop
...
The class vehicle is called
base class (or super class) and class four wheeler is called derives class (or subclass)
...
Reusability
Like library functions in procedural programming a class in Object Oriented
Programming can be distributed for further use
...
Once a class is completed and tested, it can be distributed
for the development other programs too
...
This idea saves time and
effort of a programmer
...
Suppose we have got a tested class Employee and we
have to design a new class for Manager
...
We can add some more features to class Manager using all features of
class Employee
...
7
...
The polymorphism allows different objects
to respond to the same operation in different ways, the response being specific to the type
of object
...
Example of polymorphism in OOP is operator overloading, function overloading
...
For example operator symbol ‘+’ is used for arithmetic operation between two
numbers, however by overloading (means given additional job) it can be used over
Complex Object like currency that has Rs and Paisa as its attributes, complex number
that has real part and imaginary part as attributes
...
When same function name is used in defining different function to operate on
different data (type or number of data) then this feature of polymorphism is function
overloading
...
csitnepal
...
Dynamic binding
The linking of a function call to the code to be executed in response to the call is called
binding
...
Function overloading and
operator overloading construct in OOP are the examples of early binding
...
This type of polymorphism occurring at compile time
is called compile time polymorphism
...
It is achieved at run time so called as run
time polymorphism
...
If classes Circle, Box, and Triangle are derived from
same function draw()
...
9
...
That is a
function is invoked for a piece of data
...
A message is sent to an object
...
An Object-Oriented program consists of set of objects that communicate with each other
...
A
message for an object is a request for execution of a procedure and therefore will invoke
a function or procedure in receiving object that generate the desired result
...
In word, the message for an object is
a request for the execution of a function belonging to an object which generates the
desired result for the given argument
...
fee (name) ;
object message information
Communication between the objects takes place as long as their existence
...
In above example student is
regarded as an object sending the message fee to find the fee to be paid by the student
with the given name
...
csitnepal
...
Simula
(1967) is generally accepted as the first language to have the primary features of an
object-oriented language
...
In around 1972 to 1980, a
pure object-oriented programming language Smalltalk was developed
...
It was designed specifically to facilitate and enforce Object Oriented methods
...
Apart from this, some languages like C++, Perl are historically procedural languages, but
have been extended with some Object Oriented features
...
They are called object-based languages
...
1
...
This language was developed by Alen Kay, Dan Ingalls, Adele, Goldberg at Xerox Palo
Alto Research center (PARC)
...
The development
of this language is influenced by language like Lisp, Simula, Logo, and Sketchpad
...
In smalltalk, objects are called instance variables
...
It offers
fully automatic garbage collection and deallocation is performed by a built in garbage
collector
...
New objects are
created using the same message passing mechanism used for operations on objects
...
The syntax is very
unusual and this leads to learning difficulties for programmers who are used to
conventional language syntax
...
All attributes
of super class are available to all its descendants
...
Also
multiple inheritance is not supported by standard implementation of Smalltalk
...
Example Program of Smalltalk:
Transcript show: 'Hello, world!'
In the above code, the message 'show:' is sent to the object 'Transcript' with the String
literal 'Hello, world!' as its argument
...
ep
a
itn
Page 9
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
2
...
The SUN says "Java is a new, simple, object
oriented, distributed, portable, architecture natural, robust, secure, multi-threaded,
interpreted, and high performance programming language"
...
Java was initially called "Oak"
...
The objective of Java was "Write Once, Run Anywhere"
(WORA)
...
Major web browsers soon incorporated the ability to run
secure Java applets within web pages
...
With the advent of
Java 2, new versions had multiple configurations built for different types of platforms
...
J2SE was the designation for the Standard Edition
...
In 1997, Sun Microsystems approached the ISO/IEC JTC1 standards body and later the
Ecma International to formalize Java, but it soon withdrew from the process
...
At
one time, Sun made most of its Java implementations available without charge although
they were proprietary software
...
Sun distinguishes
between its Software Development Kit (SDK) and Runtime Environment (JRE) which is
a subset of the SDK, the primary distinction being that in the JRE, the compiler, utility
programs, and many necessary header files are not present
...
On 8 May 2007 Sun finished the process, making
all of Java core code open source, aside from a small portion of code to which Sun did
not hold the copyright
...
Java applications are typically compiled to bytecode which
can run on any Java virtual machine (JVM) regardless of computer architecture
...
One
should be able to write a program once, compile it once, and run it anywhere
...
The
code is then run on a virtual machine (VM), a program written in native code on the host
hardware that interprets and executes generic Java bytecode
...
Note that, although there is an explicit
compiling stage, at some point, the Java bytecode is interpreted or converted to native
machine code by the JIT ( Just In Time) compiler
...
java
public class Hello {
public static void main(String[] args) {
System
...
println("Hello World!");
}
}
ep
a
itn
Page 10
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
3
...
NET fromework and later approved as a standard by ECMA and ISO
...
It was develop by Microsoft in 2000
and was standarderised by ECMA (European Computer Manufactor Association) in
2003
...
Console
...
C++
The programming language C++ was developed by Bjarne Stroustrup at Bell Lab in New
Jersey in early 1980 s as extension of C
...
In 1983 it was
renamed to C++
...
++ is increment operator
in C/C++
...
The C++ programming language standard was ratified in 1998 as
ISO/IEC 14882:1998, the current version of which is the 2003 version, ISO/IEC
14882:2003
...
C++ is regarded as a mid-level
language, as it comprises a combination of both high-level and low-level language
features
...
The C++ language corrects most of the deficiencies of C by
offering improved compile time type checking and support for modular and object
oriented programming
...
Example Program of C++:
itn
Page 11
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Advantages of OOP
Object oriented programming contributes greater programmer productivity, better quality
of software and lesser maintenance cost
...
l
#include
using namespace std;
int main()
{
cout<<’Hello, World!’);
return 0;
}
·
·
·
·
·
·
·
·
·
·
·
Through data hiding, programmer can build secure programs that cannot be
invaded by code in other pats of the program
...
Classes are
also available as library class in the standard library of the language
...
Software complexity is less severe than conventional programming techniques
...
The limitation realized in base class can be fulfilled in derived class without
writing even a single piece of code in the base class
...
System can be easily upgraded from small to large systems
...
Models real world system perfectly
...
Disadvantages of OOP
· Compiler and runtime overhead
...
· An object's natural environment is in RAM as a dynamic entity but traditional
data storage in files or databases
· Re-orientation of software developer to object-oriented thinking
...
· Benefits only in long run while managing large software projects
...
Basic program constructs in C++
Introduction to C++
C++ is an object oriented programming language
...
It was developed on the base of C programming language
and the first added part to C is concept of Class
...
Later name was changed to C++ on the basis of idea of increment
operator available in C
...
The first C++ program
Following is a sample program in C++ that prints a string on the screen(monitor)
...
csitnepal
...
h>
int main()
{
cout<<”Hi Everybody”;
return 0;
}
Like in C, functions are the basic building block in C++
...
When a C++ program executes, the first statement that executes will be the first statement
in main () function
...
It may also call other stand-alone functions
...
So, it returns one integer value to the
operating system
...
So,
main ()
{
……
...
Many operating systems test
the return values
...
If the returned value (exit value) is non zero, it would mean
that there was problem
...
A
comment may start at the beginning of a line or anywhere in the line and whatever
follows till the end of that line is ignored
...
If we need to
comment multiple lines, we can write as
// this is an
// example
// of multi line comments
The C comment style /*…………
...
The output operator ( Output using “cout”)
The statement: cout<<”Hi Everybody”; in the above example prints the phrase in
quotation marks on the screen
...
csitnepal
...
The operator << is called ‘insertion’ or ‘put to’ operator
...
cout<In the above case, the statement will display the content of the variable ‘a’
...
This causes the program to wait for the user to type and give some
input
...
Here, the identifier ‘cin’, pronounced as ‘see in’ is an object of standard input stream
...
It extracts or gets value
from keyboard and assigns it to the variable on its right
...
cout<cin>>x>>y>>z;
These are perfectly legal
...
Similarly, the cin statement first
reads a value and stores in x, then reads again and stores in y and then in z
...
The iostream header file
The directive ‘#include
h file to the program
...
So, the header file iostream should always be included at the
beginning if we need to use cin, cout, << and >> operators in our program
...
Keywords, identifiers,
constants, strings and operators are tokens in C++
...
Some keywords are int,
auto, switch, case, do, else, public, default, continue etc
...
This specified
task is repeated each time the function is called
...
They increase the modularity of the programs and reduce code redundancy
...
The main function may call other functions, which in turn will again
call other functions
...
Once the statements of the function get executed (when the last closing bracket is
encountered) the program control return to the place from where this function was called
...
csitnepal
...
Hierarchy of C++ Data types
Enumerated Data Types
Like structures, enumerated data type is another user defined data type
...
They are used when we know a finite list of values
that a data type can take on or it is an alternative way for creating symbolic constants
...
csitnepal
...
We can also use relational
operators when suitable
...
Once we specify the data type, we need to define variables of that type
...
shape s1,s2;
l
Eg
...
If other values are
given, error will be generated
...
h>
#include
It provides an alias
(another name) for a previously defined variable
...
Source: www
...
com (By:Tej Bahadur Shahi)
Page 16
ep
a
-
itn
-
A reference variable must be initialized at the time of declaration, since this will
establish correspondence between the reference and the data object which it
names
...
The notation int & means reference
to integer type data
...
cs
-
l
In the above example, we are creating a reference variable ‘sum’ for an existing variable
‘total’
...
Both of these names refer to same data
object in memory
...
Eg- the statement
total = total + 200; will change value of ‘total’ to 300
...
So the statements
cout<
-
Another application of reference variable is in passing arguments to function
...
The called function creates a new value of the
same type as the argument and copies the argument value into it
...
Although this provides security to the actual data, it is not
suitable if we need to modify actual data
...
Instead of value, a reference to the original variable is passed to the called function
...
The advantage is that the called function can use
actual variable and not its copy only
...
(Example- swapping values)
Manipulators
The manipulators are operators used with insertion operator “<<’ to format or manipulate
the data display
...
endl manipulator causes a linefeed to be inserted into the output stream
...
e the cursor
moves to next line
...
Egcout<<”Kathmandu”<
See output
setw manipulator specify a field width to a number or string that follows it and force
them to be printed right justified
...
Egx = 456; y = 40;
cout<
...
For y, it will specify again space of width 5,
right justifies and prints
...
csitnepal
...
This specified
task is repeated each time the function is called
...
They increase the modularity of the programs and reduce code redundancy
...
The main function may call other functions, which in turn will again
call other functions
...
Once the statements of the function get executed (when the last closing bracket is
encountered) the program control return to the place from where this function was called
...
Syntax:
return-type function-name(datatype1, datatype2, …,datatype n);
Function Call
Function call is the process of making use of function by providing it with the parameters
it needs
...
function-name (argument1, argument2,
...
A function is defined as follows,
return-type function-name(datatype1 variable1, datatype2 var2, …
...
; //body of the function
………………
...
But it does not
work on any general function
...
When the arguments are missing from function
call, default value will be used for calculation
...
csitnepal
...
h>
float interest(int p, int t = 5, float r = 5
...
If we give, as input, values for pr,
rate and yr as 5000, 10 and 2, the output will be
1000 500 1250
NOTE: The default arguments are specified in function declaration only and not in
function definition
...
We must add defaults from right to
left
...
Default arguments are used in the situation where some arguments have
same value
...
, interest rate in a bank remains same for all customers for certain
time
...
However, every time a function
is called, it takes a lot of extra time in executing a series of instructions
...
When a
function is small, considerable amount of time is spent in such overheads
...
csitnepal
...
To eliminate the cost of calls to small functions,
C++ proposed a new feature called INLINE function
...
A function is made inline by using a keyword “inline” before the function definition
...
inline void calculate_area(int l,int b)
{
return(l * b);
}
It should be noted that, the inline keyword merely sends request, not a command, to a
compiler
...
Some situations where inline
expansion may not work are
- for functions having loop, switch or goto statements
- for recursive functions
- functions with static variables
- for functions not returning values, if a return statement exists
Inline functions must be defined before they are called
...
#include
453 * lbs);
}
main()
{
float lbs, kgs;
cout<<”Enter weight in lbs:”;
cin>>lbs;
kgs=lbtokg(lbs);
cout<<”Weight in kg is ”<
}
Exercise:
When do we use inline function? Explain with example
...
itn
Page 20
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Function that share the same name are said to be overloaded functions and the process is
referred to as function overloading
...
e
...
Each redefinition of a function must use different
type of parameters, or different sequence of parameters or different number of
parameters
...
When we call the function, appropriate function is called based on the
parameter passed
...
For egint add(int , int ) and float add(int, int)
A function call first matches the declaration having the same number and type of
arguments and then calls the appropriate function for execution
...
The function selection will involve the following steps:
- the compiler first tries to find an exact match in which the types of actual
arguments are the same and uses that function
- if an exact match is not found, the compiler uses the integral promotion to the
actual parameters, such as,
char to int
float to double to find the match
- If both of the above fail, the compiler tries to use the built-in conversions and
then uses the function whose match is unique
...
h>
//function declaration
float perimeter(float);
int perimeter(int,int);
int perimeter(int,int,int);
main()
{
cout<<”Perimeter of a circle: ”<
csitnepal
...
14*r);
}
int perimeter(int l,int b)
{
return(2*(l+b));
}
int perimeter(int a,int b,int c)
{
return(a+b+c);
}
In the above program, a function “perimeter” has been overloaded
...
56
Perimeter of a rectangle 40
Perimeter of a triangle 30
Recursive function
Recursion is a powerful technique of writing complex algoriths in an easy way
...
In this technique , a large problem is divided into smaller
problem of similar nature as original problem
...
Hence to implement this techinique, a
programming language support the function that is capable of calling itself
...
csitnepal
...
Structures were used
to group logically related data items
...
Once the
structure type was defined, we can create variables of that type
...
struct student
{
l
int fact(int num)
{
If(num==0)
Return 1;
Else
Return (num*fact(num-1));
}
char name[15];
int roll_no;
float total_marks;
};
For the above structure, we can define variables like
struct student s1,s2,s3;
But there are certain limitations in C structures
...
The structure members can be accessed using
structure variable by any function anywhere in the scope
...
C++ supports all the features of structures as defined in C
...
It attempts to bring the user-defined types
as close as possible to the built-in data types, and also provides a facility to hide the data
which is one of the main precepts of OOP
...
It can also declare
some of its members as private so that they can not be accessed directly by the external
functions
...
In other words, the keyword struct can be omitted in the declaration of
structure variables
...
There
is very little syntactical difference between structures and classes in C++ and, therefore,
they can be used interchangeably with minor modifications
...
The only difference between a structure and a class in C++ is that, by default, the
members of a class are private, while, by default, the members of a structure are public
...
This entire collection can be called a new data-type
...
Classes allow the data and functions to be hidden, if necessary, from external use
...
These variables are called Objects
...
csitnepal
...
- class declaration
- function definition
Syntax:
class class-name
{
private:
Variable declarations
Function declarations
public:
Variable declarations
Function declarations
};
the class specification starts with a keyword “class” (like “struct” for structures),
followed by a class-name
...
The body of the class is enclosed within braces and terminated by a semicolon
...
The variables
are, specially, called data members while the functions are called member
functions
...
Those keywords are termed as access-specifiers, they are also termed as visibility
labels
...
o The class members that have been declared as private can be accessed
only from within the class
...
e
...
o On the other hand, public members can be accessed from anywhere
outside the class (using object and dot operator)
...
csitnepal
...
Generally, data within a class is made private and
the functions are public
...
However, it is not always necessary that
l
o All the class members are private by default
...
o If both the labels are missing, then, by default, all the members will be
private and the class will be completely inaccessible by the outsiders
(hence it won’t be useful at all)
...
In some cases, data may be public too and
functions may be private
...
csitnepal
...
But this works only for the public
members
...
The general format is
class-object
...
l
Creating Objects
Once a class has been specified (or declared), we can create variables of that type (by
using the class name as datatype)
...
The above statement creates a variable t1 of type Test
...
So, t1 is called object of class Test
...
Test t1, t2, t3;
When object is created, the necessary memory space is allocated to this object
...
Objects can be
created when a class is defined, as follows:
class Employee
{
int id;
char name[20];
public:
void getname();
void putname();
}e1,e2,e3;
The objects are also called instances of the class
...
class-object
...
obj1
...
data2 + obj1
...
members
...
function-name(argument-list);
eg
...
getdata();
In the above example, e1 is an object of a class and getdata() is its member function
...
The private data and functions of a class can be accessed only through the member
functions of that class
...
class A
{
int x,y;
void fu1();
public:
int z;
void fu2();
};
- -------- -- ---------- A obj1;
obj1
...
z = 0; //valid
obj1
...
fu2(); //valid
Defining member functions (i
...
writing the body of a function):
Member functions can be defined in two ways
...
Irrespective of the
place of definition, the function should perform the same task
...
csitnepal
...
(As has been done in the previous example of class
Employee)
...
The functionname is proceeded by
- return-type of the function
- class-name to which the function belongs
- symbol with double colons(::)
...
This operator tells the compiler that the function belongs to the class
class-name
...
void Employee::getdata()
{
--------- - - - - - - -- - //function body
- - - -- - -- -}
In this example, the return-type is void which means the function “getdata()” doesn’t
return any value
...
The argument list is also empty
...
These classes can use same
function name
...
- Member functions can directly access private data of that class
...
(Exception is friend function)
- A member function can call another member function directly, without using
the dot operator
...
If it is done, the function is treated as an inline function
...
Eg
...
csitnepal
...
So, it will act like an inline function
...
Eg
...
This qualifier will
make the function ‘getdata()’ an inline
function
Nested Member Functions
An object of the class using dot operator generally, calls a member function of a class
...
This is known as “Nesting of Member Functions”
...
#include
csitnepal
...
e member function called from another
member function
...
read( );
a1
...
But in some cases, we
may need a private function to hide them from outside world
...
Object of the class
cannot invoke it using dot operator
...
class A
{
int a,b;
void read(); //private member function
public:
void update();
void write();
};
void A::update()
{
read(); //called from update() function
...
}
ep
a
itn
Page 29
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
------------ ------------- If a1 is an object of A, then the following statement is not valid
...
read();
This is because, read() is a private member function, hence cant be called using object
and dot operator
...
- But, we have to note one thing
...
All the objects belonging to the particular class will use the
same member functions; no separate space is allocated for member functions
when objects are created
...
So,
space for member data is allocated separately for each object
...
datamemberN
datamember1
datamember2
…
...
datamemberN
fig: Objects in memory
itn
Page 30
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Array of Objects
Array can be created of any data-type
...
Such an array is called an array of
objects
...
we had specified a class called Employee in some example above
...
Member function
Employee dept1[10];
...
The arrays dept1 and dept2 both has member function N items are objects of type
ten items (These
Employee)
...
getdata();
dept2[3]
...
There
are two ways of doing this
...
So, the changes
made to the object inside the function do not affect the actual object
...
So, changes made to the
object inside the function are reflected in the actual object
...
Eg
...
inches + h2
...
feet + h2
...
csitnepal
...
getHeight();
h2
...
sum(h1,h2);
cout<<”Height 1:”<
...
putHeight();
cout<<”Height 3:”<
...
NOTE: A function can, not only, take objects as arguments, but they can also
return object
...
In the above program if we modify the function sum() as follows:
Height Height::sum(Height h1,Height h2) //function with return type
Height
{
Height h3;
h3
...
inches + h2
...
feet= h3
...
inches= h3
...
feet = h3
...
feet + h2
...
Friend Function
A function is said to be a friend function of a class if it can access the members
(including private members) of the class even if it is not the member function of this
class
...
ep
a
itn
Page 32
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Characteristics of a friend function:
- A friend function can be either global or a member of some other class
...
- It cannot be called by using the object of the class since it is not in the scope
of the class
...
- Unlike member functions, it cannot access member names directly
...
x)
- It, generally, takes objects as arguments
...
Its definition is written somewhere
outside the class
...
class Avg
{
int n1,n2;
public:
void getn()
{
cin>>n1>>n2;
}
friend int average(Avg a);
};
//here “friend” is a keyword to specify that the function declared is a friend
function
//int is a return type of the friend function
//average is the name of the friend function
//Avg is the type of the argument type
//a is an argument
itn
Page 33
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
int main()
{
Avg obj;
obj
...
Perhaps the
function will take objects of the two classes as arguments, and operate on their private
l
int average(Avg a) //friend function definition
{
return((a
...
n2)/2);
}
data
...
Here is an example that
shows how friend functions can act as a bridge between two classes
...
h>
#include
...
csitnepal
...
data+b
...
get_data();
bb
...
In
some cases, it may be necessary that all objects of a class have access to the same copy of
a single variable
...
- Only one copy of the static member is created for the entire class and is shared
by all the objects of that class, no matter how many objects are created
...
- It is initialized to zero when the first object of its class is created
...
A static variable is declared using the “static” keyword
...
It is necessary since static data member are stored
void put_count()
separately, rather than as a part of the object
...
}
Eg
...
put_count();
b
...
put_count();
return(0);
ep
a
itn
Page 35
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
}
Output:
123
Static Member Function
In a class, functions can also be declared as static
...
class_name::function_name
ep
a
itn
Page 36
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Example
class A
{
int no;
static int count;
//static member
public:
void set_no()
{
count++;
no = count;
}
void put_no()
{
cout<<”No
...
set_no();
a2
...
set_no();
a2
...
put_no();
a2
...
Constructors and Destructors
We have seen, so far, a few examples of classes being implemented
...
For example, the statement
t
...
Similarly, the statement
t
...
All these function call statements are used
with the appropriate objects that have already been created
...
One of the aims of C++ is to create user-defined data types such as class that behave very
similar to the built-in types
...
For example,
int x = 10;
float y = 56
...
Similarly, when a variable of built-in type goes out of scope, the compiler automatically
destroys the variable
...
There are some features of class that enable us to initialize the objects when they are
created and destroy them when their presence is no longer necessary
...
csitnepal
...
This is known as automatic initialization of objects
...
Constructors
A constructor is a special member function whose task is to initialize the objects of its
class
...
The constructor is invoked whenever an
object of its associated class is created
...
-
They are also used to allocate memory for a class object
...
Constructor’s name is same as that of class name
...
They do not have return types, not even void and therefore, and they cannot return
any values
...
Constructor is NOT called when a pointer of a class is created
...
- Default constructors
- Parameterized Constructors
- Copy Constructors
Default Constructors
A constructor that does not take any parameter is called default constructor
...
1
...
And it does not do anything other than
allocating memory for the class object
...
If we provide a constructor without any arguments then that is the default
constructor
...
csitnepal
...
If we provide constructor with all default arguments, then that can also be
considered as the default constructor
...
Arguments are
passed when the objects are created
...
- by calling the constructor explicitly
- by calling the constructor implicitly
For eg
...
ep
a
itn
Page 39
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Copy Constructor
A copy constructor is called when an object is created by copying an existing object
...
A obj2(obj1);
The above statement would define the object obj2 and initialize it to the values of obj1
...
A copy constructor takes a reference to an object of the same class as itself (as an
argument)
...
When no copy
constructor is defined, the compiler supplies its own copy constructor
...
However, if obj1 and obj2 are objects, this
statement is legal and simply assigns the values of obj1 to obj2, member by member
...
Eg
...
info;
}
void display()
{
cout< }
};
int main()
{
ep
a
itn
Page 40
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Data d1(5); //parameterized constructor is called
...
Data d3=d2; //again a copy constructor is called here
...
display();
cout<<”An info stored in d2”;
d2
...
display();
cout<<”An info stored in d4”;
d4
...
The first one d1 calls the parameterized
constructor, while the other two calls the copy constructor
The output will be
An info stored in d1 5
An info stored in d2 5
An info stored in d3 5
An info stored in d4 5
Constructor Overloading
The process of sharing the same name by two or more functions is referred to as function
overloading
...
In the above example of class Data, we have defined three constructors
...
The second gets invoked when we supply
one argument, while the third one gets invoked when an object is passed as an argument
...
Data obj1;
This statement would automatically invoke the first one
...
Eg
...
csitnepal
...
display();
obj2
...
display();
return(0);
}
Output:
000
5 10 15
6 10 20
In this program, there are two constructors
...
Such
a constructor is called a constructor with default argument
...
It is important to distinguish between the default constructor A::A() and the default
argument constructor A::A (int x = 0)
...
When called with no arguments, it becomes a
default constructor
...
ep
a
itn
Page 42
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Example
#include
...
h>
class test
{
int x,y;
public:
//test() // No need to use this default constructor
//{}
test(int p=10,int q = 20) // when this constructor is called with no arguments, it
{
// becomes default constructor
x = p;
y = q;
}
void display()
{
cout<<"X = "< }
};
void main()
{
int x,y;
cin>>x>>y;
test t(x,y); // call to default argument constructor
t
...
display();
getch();
}
Dynamic initialization of objects
Class objects can be initialized dynamically (i
...
at the run time)
...
Advantage: various initialization formats can be provided using constructor overloading
...
l=1;
b=1;
area=1;
}
Area(int a, int br)
{
Area()
l
{
void main()
{
int l,b,area;
Area a1,a2;
public:
int l,b,len;
cin>>l>>b;
a1=Area(l,b);
cin>>len;
a2=Area(len);
--------- - -- - - - - - }
l=a;
b=br;
ep
a
class Area
{
cs
itn
Source: www
...
com (By:Tej Bahadur Shahi)
Page are
NOTE: In dynamic initialization, we 43 explicitly calling
the required constructor
...
area=l*b;
}
Area(int a)
{
l=a;
b=0;
area=l*l;
}
};
Destructors
Destructors are the special function that destroys the object that has been created by a
constructor
...
Destructors, too, have special name, a class name
preceded by a tilde sign (~)
...
A destructor for the class Area will look like
~Area()
{-----------}
Destructor gets invoked, automatically, when an object goes out of scope (i
...
exit from
the program, or block or function)
...
Destructor
never takes any argument, nor does it return any value
...
#include
...
h>
class A
{
static int count;
public:
A()
{
count++;
cout< }
~A()
{
cout< count--;
}
};
int A::count;
ep
a
itn
Page 44
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
main()
{
A a1,a2,a3;
getch();
return 0;
}
Operator Overloading
The concept of overloading can be applied to operators as well
...
It provides a flexible option for
the operations of new definitions for most of the C++ operators
...
In general,
a = b + c; works only with basic types like ‘int’ and ‘float’, and attempting to
apply it when a, b and c are objects of a user defined class will cause complaints from the
compiler
...
There are two types of operator overloading
Unary operator overloading and
Binary operator overloading
Unary operator overloading
Unary operators are those operators that act on a single operand
...
The following program overloads the ++ unary operator for the distance class
to increment the data number by one
...
csitnepal
...
display();
}
In the above example, the ++ unary operator has been overloaded in the function void
Distance :: operator ++(void)
...
This function is called at the second line ‘++dist’ in the main
...
list)
{
//func body
}
The keyword ‘operator’ is used to overload an operator
...
//Another Example - overloading unary minus operator
ep
a
itn
Page 46
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
class abc
{
int x,y,z;
public:
void getdata(int a,int b,int c)
{
x = a;
y = b;
z = c;
}
void display()
{
cout< }
void operator -();
};
void abc::operator-()
{
x = -x;
y = -y;
z = -z;
}
main()
{
abc a;
a
...
display();
-a;
a
...
If we use a statement like this
c1 = ++c2;
For this we have to define the ++ operator to have a return type object of a class in the
operator++ function
...
the example given
below illustrates this
...
csitnepal
...
put_count();
c2
...
put_count();
c2
...
What about postfix, where the
variable is incremented after its value is used in the expression?
c1++
to make both versions of the increment operator work, we define two overloaded ++
operators as follows
class Counter
{
int count;
public:
Counter()
{
count = 0;
}
Counter(int c)
{
count = c;
}
ep
a
itn
Page 48
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Counter operator++()
{
return Counter(++count);
}
Counter operator++(int)
{
return Counter(count++);
}
void put_count()
{
cout< }
};
main()
{
Counter c1,c2,c3;
c1
...
put_count();
c2 = ++c1;
c3 = c2++;
c1
...
put_count();
c3
...
The one, for
prefix notation, is
Counter operator ++()
The one, for postfix notation, is
Counter operator ++(int)
The only difference is the int in the parentheses
...
It’s simply a signal to the compiler to create the postfix version of
the operator
...
Overloading binary operators
Binary operators are those that work on two operands
...
Overloading a binary operator is similar to overloading unary operator except that a
binary operator requires an additional parameter
...
It adds two objects of type ‘distance’
...
csitnepal
...
csitnepal
...
The argument on the left side the operator (d1 here) is the
l
};
Distance Distance :: operator + (Distance d2)
{
int m = meter + d2
...
centimeter;
if(cm >= 100)
{
cm -= 100;
m++;
}
return Distance (m,cm);
}
main()
{
Distance d1(4,50);
Distance d2,d3,d4;
d2
...
operator+(d1); // usual function call syntax
d3
...
show();
return 0;
}
object of which the operator is a member
...
Overloading Binary Operators Using Friend Function
Friend functions may be used in the place of member functions for overloading a binary
operator, the only difference being that a friend function requires two arguments to be
explicitly passed to it, while a member function requires only one
...
csitnepal
...
meter + d2
...
centimeter + d2
...
getDist();
d3 = d1 + d2;
d3
...
feet && inch == e
...
csitnepal
...
4);
equal e2(6,4
...
h>
#include
...
h>
#define SZ 20
class string
{
private:
char str[SZ];
public:
string()
{
strcpy(str," ");
}
string(char s[])
{
strcpy(str,s);
}
void getstring()
{
cout<<"\nEnter a string ";
cin>>str;
}
int operator ==(string ss)
{
return(strcmp(str,ss
...
csitnepal
...
getstring();
if(s3 == s1)
cout<<"\nYou typed Nepal";
else if(s3 == s2)
cout<<"\nYou typed Kathmandu";
else
cout<<"\nNot of both";
getch();
return 0;
}
ep
a
itn
Page 54
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//Overloading + operator to concatenate two strings
#include
...
h>
#include
...
str) < SZ)
{
strcpy(temp
...
str,ss
...
display();
s2
...
display();
cout< getch();
return 0;
}
ep
a
itn
Page 55
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//Overloading < operator
class line
{
int feet;
float inch;
public:
line()
{}
line(int f,float i)
{
feet = f;
inch = i;
}
void display()
{
cout< }
int operator<(line);
};
int line::operator<(line l)
{
float l1 = feet + inch/12;
float l2 = l
...
inch/12;
if(l1 return 1;
else
return 0;
}
main()
{
line l1(2,5
...
3);
if(l1 l1
...
display();
getch();
return 0;
}
Multiple Overloading
We have seen several different uses of + operator: - to add distance and to concatenate
strings
...
It selects the correct function to carry out the addition
based on the type of operand
...
ep
a
itn
Page 56
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
h>
#include
...
csitnepal
...
meter;
int cm = centimeter + d2
...
str) < SZ)
{
strcpy(temp
...
str,ss
...
getDist();
d3 = d1 + d2;
d3
...
display();
s2
...
display();
getch();
return 0;
}
General rules for overloading operators
There are some restrictions and limitations to be kept in mind while overloading
operators
...
New operators can not be created
...
It is not recommended to change the basic meaning of an operator
...
Overloaded operators follow syntax rules of the original operators
...
Friend functions can not be used to overload certain operators like =, ( ), [ ] and >
...
But those overloaded by a friend
functions take one reference argument
...
Binary operators such as +, -, *, and / must explicitly return a value
...
ep
a
itn
Page 58
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Operator Overloading Restriction
Operator functions can not have default arguments
...
*, ?:, sizeof
...
Type Conversion (Data Conversion)
We use the assignment operator (=) to assign value of one variable to another
...
We have also noticed that = assigns the value of one
user defined object to another, provided that they are of the same type
...
The compiler
does not need any special instructions to use = for the assignment of user-defined objects
such as distance objects
...
But if the variables on different sides of the = are of different types, then the type of
variable on the right side of = needs to be converted to the type of left side variable
before the assignment takes place
...
Conversion Between Basic Types
Consider the statement,
itn
Page 59
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
where intvar is of type int and floatvar is of type float
...
There are many such
l
intvar = floatvar;
conversions: from float to double, char to float and so on
...
Such conversions are implicit conversion
...
For example,
int total = 400;
float avg;
avg = float(total) / 5; // converts value of total to float before division takes place
...
Instead, we must write these routines
ourselves
...
These are sometimes
called conversion constructors
...
display();
getch();
ep
a
itn
Page 60
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
}
From User-Defined to Basic Type
When class type data is converted into basic type data, it is called class to basic type
conversion
...
This type of
conversion takes place in casting operator
...
The syntax of casting operator function is
operator typename()
{
………
...
}
This function converts a class type data to typename
...
The operator int() converts a class type object to
type int and so on
...
It must not specify a return type
...
class Stock
{
int items;
float price;
public:
Stock(int a,float p)
{
items = a;
price = p;
}
void putdata()
{
cout<<"Items: "< cout<<"Price: "< }
operator float()
{
return (items*price);
}
Stock s(45,2
...
csitnepal
...
putdata();
cout<<"Total float value = "< getch();
return 0;
}
Another example
class DistConv
{
private:
int kilometers;
double meters;
static double kilometersPerMile;
public:
// This function converts a built-in type (i
...
miles) to the
// user-defined type (i
...
DistConv)
DistConv(double mile) // Constructor with one argument
{
double km = kilometersPerMile * mile ; // converts miles to
//kilometers
kilometers = int(km);
// converts float km to
//int and assigns to kilometer
meters = (km - kilometers) * 1000 ;
// converts to meters
ep
a
itn
Page 62
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
}
DistConv(int k, float m) // constructor with two arguments
{
kilometers = k ;
meters = m ;
}
// ********Conversion Function************
operator double()
// converts user-defined type i
...
// DistConv to a basic-type
{
// (double) i
...
meters
double K = meters/1000 ;
// Converts the meters to
// kilometers
K += double(kilometers) ;
// Adds the kilometers
return K / kilometersPerMile ; // Converts to miles
}
void display(void)
{
cout << kilometers << " kilometers and " << meters << " meters" ;
}
}; // End of the Class Definition
double DistConv::kilometersPerMile = 1
...
0 ;
// Uses the constructor with one argument
DistConv d2( 2, 25
...
255 kilometers = " << ml << " miles\n" ;
ml = d1 ;
// This form also uses conversion function
// and converts DistConv to miles
d1
...
255 kilometers = 1
...
72 meters = 5 miles*/
From One Class to Another Class Type
When a data of one class type is converted into data of another class type, it is called
conversion of one class to another class type
...
csitnepal
...
The class Y type data is
converted to the class X type data and converted value is assigned to the objx
...
This type of conversion is carried out by either constructor or
a conversion function
...
We know that the casting operator function
Converts the class object of which it is a member to typename
...
In the case of conversion between objects,
typename refers to the destination class
...
e
...
The conversion takes place in the
source class and the result is given to the destination class object
...
This implies
that the argument belongs to the source class and is passed to the destination class for
conversion
...
class Kilometers
{
private:
double kilometers;
public:
Kilometers(double kms)
{
kilometers = kms;
}
void display()
{
cout << kilometers << " kilometeres";
}
double getValue()
{
return kilometers;
}
};
ep
a
itn
Page 64
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
class Miles
{
private:
double miles;
public:
Miles(double mls)
{
miles = mls;
}
void display()
{
cout << miles << " miles";
}
operator Kilometers()
{
return Kilometers(miles*1
...
getValue()/1
...
display();
cout << " = ";
k1
...
display();
cout << " = ";
m2
...
934 kilometeres
100 kilometeres = 62
...
csitnepal
...
csitnepal
...
getcode();
value = p
...
getprice();
}
};
main()
{
clrscr();
invent1 s1(100,5,140
...
putdata();
cout<<"Stock value"<<"\n";
cout<<"value = "< cout<<"Product details-invent2 type"<<"\n";
d1
...
csitnepal
...
Write a program to overload += operator
...
Write a program to overload = operator (It is already overloaded in C++)
...
3
...
4
...
Overload + operator to add two objects of class Length
...
Also facilitate the operations like L4 = L1 + 5 and L5 = 5 + L4 where L1,
L2, L3, L4 and L5 are objects of class Length
...
5
...
Assume that the class distance contains two data members (feet
(integer type) and inch (floating point type)
...
33 feet and 1 feet
= 12 inches)
6
...
e
...
Let P1
and P2 be the objects of this class where P1 is initialized to (20, 30)
...
itn
Page 68
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
7
...
Inheritance
Inheritance is the most powerful feature of object-oriented programming
...
The class inherits all the capabilities of the base class but can add refinements of
its own
...
Inheritance is also called a ‘kind of relationship’
...
Once a class has been written and tested, its features can be adapted by
other programmers whenever required
...
csitnepal
...
Inheritance
Types
There are 5 types of inheritance
1) Single Inheritance – when a class is derived from only one base class, then it is called
single inheritance
...
csitnepal
...
// body part
…
}
public:
{
…
...
}
};
class B : public A // derived class B
{
……
…
...
It can be represented as,
Base class A
Base class B
Derived class C
Egclass A
{
……
...
csitnepal
...
……
};
class C : public A, public B
{
……
...
3) Hierarchical Inheritance: When two or more than two classes are derived from one
base class, it is called hierarchical inheritance
...
………
...
……
};
class C : public A
{
………
………
};
Here two classes B and C are derived from same base class A
...
csitnepal
...
g
...
…
...
……
};
class C : public B
{
…
...
};
In this example class B is derived from base class A and class C is derived from derived
class B
...
csitnepal
...
gclass student
{
……
…
...
……
...
};
class result : public test, public sport
{
……
…
...
The class test and sport are derived from
student and class result is derived from both test and sport classes
...
itn
Page 74
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Sub-class Definition
A subclass can be defined by specifying its relationship with base class along with its
own details
...
………
};
baseclass-name
The colon indicates that the inheritance has been used
...
e
...
The visibility mode specifies whether the features of the base class are
derived privately, publicly or protectedly
...
The three visibility modes are
public
private
protected
When the base class is publicly inherited, all the public members of the base class
become public members of the derived class
...
All the protected members become protected members of the
derived class
...
So, these can not be accessed
outside the class directly through the derived class object, but might be accessed through
public functions in the derived class
...
NOTE: private members can not be inherited at all
...
When a member is defined with protected access specifier, these members can be
accessed from that class and also from the derived class of this base class
...
i
...
protected members act as public for
derived class and private for other classes
...
csitnepal
...
Consider the program
#include
...
This means, like a
private inheritance, these members can not be directly accessed through object of the
derived class
...
Whereas, unlike a private
inheritance, they can still be inherited and accessed by subsequent derived classes
...
class aclass
{
public:
void disp(void)
{
cout<<”Base”< }
};
class bclass : public aclass
{
public:
void disp(void)
{
cout<<”Derived”< }
};
void main()
{
bclass Bvar;
Bvar
...
If the function is invoked from an object of the derived class, then the function in
the derived is executed
...
Ambiguities in Multiple Inheritance
When a class inherits from multiple base classes, a whole part of ambiguities creep in
...
csitnepal
...
h>
class base1
{
public:
void disp(void)
{
cout<<”Base1”< }
};
class base2
{
public:
void disp(void)
{
cout<<”Base2”< }
itn
Page 77
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Here, the reference to disp() is ambiguous because the compiler does not know whether
disp() refers to the member in class base1 or base2
...
base1::disp();
Dvar
...
That is, the members can be
redefined in the derived class
...
};
class derived : public base1, public base2
{
public:
void disp(void)
{
base1::disp();
base2::disp();
cout<<”Derived class”< }
};
void main()
{
derived Dvar;
Dvar
...
disp(); // Ambiguous
}
}
Another ambiguity that arises in multiple inheritance is the possibility of the derived class
having multiple copies of the same base class
...
B and C in
turn are derived from class A
...
There are two ways of resolving this ambiguity
...
Containership
When a class contains object of another class as its member data, it is termed as
containership
...
Containership
is also termed as “class within class”
...
A obj1;
…
...
So
B is the container class
...
csitnepal
...
Containership is useful with classes that act like a data type
...
l
‘containership’ is also called ‘has-a’ relationship
...
This is
because B has all the characteristics of A, and in addition some of its own
...
itn
Page 79
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
class Manager
{
char name[20];
int age;
public:
void getdata()
{
cin>>name>>age;
}
void putdata()
{
cout< }
};
class Employee // Employee is container class
{
char department[20];
Manager m; // Object of class Manager
public:
void getdata()
{
m
...
putdata();
cout< }
};
void main()
{
Employee e;
e
...
putdata();
getch();
}
Abstract Class
An abstract class is one that is not used to create objects
...
It is a design concept in program development and provides a
base upon which other classes may be built
...
When the same class is
inherited more than once via multiple paths, multiple copies of the base class members
are created in memory
...
A base class inheritance can be specified as a virtual using
the virtual qualifier
...
…
...
…
...
};
class C : public B1, public B2
{
……
……
};
Keywords ‘virtual’ and ‘public’ can be used in either way
...
csitnepal
...
However, if any base
class contains a constructor with one or more arguments, then it is mandatory for the
derived class to have a constructor and pass the arguments to the base class constructors
...
Thus, it
makes sense for the derived class to pass arguments to the base class constructor
...
Since there is only one copy, there is no ambiguity
...
Since the derived class takes the responsibility of supplying initial values to its base
classes, we supply the initial values that are required by all the classes together, when a
derived class object is declared
...
The constructor of the derived class receives the entire list of values as its arguments and
passes them onto the base constructors in the order in which they are declared in the
derived class
...
Example-
ep
a
itn
Page 81
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
5,50,60);
g
...
show_y();
g
...
Since the derived class contains more than one
Constructors and/or Destructors, it becomes confusing which one will be called when
...
This article will clear all this!
Consider the following example program:
// -- INHERITANCE -// Constructors, Destructors
// and Inheritance
#include
...
csitnepal
...
One more example will clear the confusions, if any
...
h>
ep
a
itn
Page 83
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
// base class (1)
class base
{
public:
base(){cout<<"Constructing Base\n";}
~base(){cout<<"Destructing Base\n";}
};
// derived class
// derived form 'base'
class derived1:public base
{
public:
derived1(){cout<<"Constructing Derived1\n";}
~derived1(){cout<<"Destructing Derived1\n";}
};
// derived from a derived class
// 'derived1'
class derived2:public derived1
{
public:
derived2(){cout<<"Constructing Derived2\n";}
~derived2(){cout<<"Destructing Derived2\n";}
};
void main(void)
{
derived2 obj;
// do nothing else, only
// construct and destruct
// the inherited class object
}
OUTPUT:
Constructing Base
Constructing Derived1
Constructing Derived2
Destructing Derived2
Destructing Derived1
Destructing Base
itn
Page 84
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Lab Sheet - 3
Employee
Name
ID
getdata()
putdata()
Manager
ComputerOperator
Department
Typing_Speed
getdata()
putdata()
getdata()
putdata()
1
...
Also write a
main() function to test the classes, Manager and ComputerOperator, by creating
their objects, taking input and displaying the corresponding values
...
Imagine a college hires some lecturers
...
Create a class called lecturer that stores the
ID, and the name of lecturers
...
Each of these three classes should have a readdata() function to get its
data from the user, and a printdata() function to display its data
...
3
...
Create a class Automobile that stores production
date and price
...
Each
of these classes should have member functions to get data and set data
...
itn
Page 85
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
4
...
From this class derive two classes: Bowler and Batsman
...
Use appropriate member functions
in all classes to read and display respective data
...
Define a base class Shape having data member radius (int)
...
Write methods to compute the area of
circle and sphere
...
Create classes Book having data members name of author (string), price (float)
and class Stock having data members number of books (int) and category (string)
...
All the classes should have functions having same name
...
Virtual Function and Run Time Polymorphism
Pointers
Pointers have a reputation for being hard to understand
...
Addresses are numbers, just as they
are for houses on a street
...
If you have 1MB of
memory, the highest address is 1,048,575; for 16 MB of memory, it is 16,777,215
...
New and Delete Operator
Pointer provides the necessary support for C++ powerful dynamic memory allocation
system
...
ep
a
itn
Page 86
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
For eg- int arr[100];
reserves memory for 100 integers
...
We must know at the time we write the program how big the
array will be and it is not always possible to predict what the size of the array will be
...
This capability is provided by the new operator
...
The syntax for the
new operator is
= new ;
where = pointer variable
= char, int, float and so on
type of variable mentioned on the left hand side and the type mentioned on the right hand
side should match
...
For egchar *cptr;
cptr = new char[10];
allocates 10 bytes of memory and assigns the starting address to cptr
...
To ensure safe and efficient use of
memory, the new operator is matched by a corresponding delete operator that returns
memory to the operating system
...
However, this address is no longer valid, the memory it
points to may be changed to something entirely different but we do not use pointers
memory that has been deleted
...
For egdelete[] cptr;
ep
a
itn
Page 87
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//Example program that makes use of new and delete operator
#include
...
h>
class test
{
int x;
public:
void input()
{
cin>>x;
}
void display()
{
cout< }
};
main()
{
test *t = new test;
t->input();
t->display();
delete t;
getch();
return 0;
}
Polymorphism
In the programming sphere, polymorphism is broadly divided into two parts- the first part
being static polymorphism- exhibited by overloaded functions and the second being
dynamic polymorphism exhibited by late binding
...
csitnepal
...
A function is said to exhibit dynamic polymorphism when it exists in
more than one form, and calls to its various forms are resolved dynamically when the
l
Static Polymorphism
Static polymorphism refers to an entity existing in different physical forms
simultaneously
...
The various types of parameters are
specified in the function declaration, and therefore the function can be bound to the calls
at compile time
...
The term early binding
stems from the fact that when the program is executed, the calls are already bound to the
appropriate functions
...
Consider the following function
declaration
...
This resolution is done at compile time
...
The term late binding refers to the resolution of the function to their
associated methods at run time instead of compile time
...
The compiler is unable to bind a call to a method since resolution depends
on the context of the call
...
Virtual Functions
Virtual means existing in appearance but not in reality
...
A function is made virtual by placing the keyword virtual
before its normal declaration
...
ep
a
itn
Page 89
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
h>
class Base
{
public:
void show()
{
cout<<"Base\n";
}
};
class Derv1 : public Base
{
public:
void show()
{
cout<<"Derv1\n";
}
};
class Derv2 : public Base
{
public:
void show()
{
cout<<"Derv2\n";
}
};
int main()
{
Derv1 d1;
Derv2 d2;
Base *ptr; // pointer to base class
ptr = &d1;
ptr->show();
ptr = &d2;
ptr->show();
getch();
return 0;
}
itn
Page 90
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Virtual Member Functions Accessed with Pointers
Let’s make a single change in the above program
...
#include
...
h>
class Base
{
public:
virtual void show()
{
cout<<"Base\n";
}
};
class Derv1 : public Base
{
public:
void show()
{
cout<<"Derv1\n";
}
};
class Derv2 : public Base
{
public:
void show()
{
cout<<"Derv2\n";
}
l
Output of the program
Base
Base
The function in the base class is always executed
...
};
int main()
{
Derv1 d1;
Derv2 d2;
Base *ptr;
ptr = &d1;
ptr->show();
ptr = &d2;
ptr->show();
getch();
return 0;
}
Output of the program
Derv1
Derv2
Now, as you can see, the member functions of the derived classes, not the base class, are
executed
...
So the same function call,
ptr->show();
executes different functions, depending on the contents of ptr
...
Here,
the compiler does not know what class the contents of ptr may contain
...
Which version of show()
does the compiler call? In fact the compiler does not know what to do, so it arranges for
the decision to be deferred until the program is running
...
Abstract Classes and Pure Virtual Functions
An abstract class is one that is not used to create objects
...
A class is made an
abstract by placing at least one pure virtual function in the class
...
i
...
a pure virtual function can be
declared by equating it to zero
...
csitnepal
...
The =0 syntax is simply how we will tell the compiler that a function will be
pure
...
If a class does not
override the pure virtual function, then it becomes an abstract class itself, and we can not
instantiate objects from it
...
We can not create objects of the abstract class
...
This allows an abstract class to be used as a base class, pointers to which
can be used to select the proper virtual function
...
csitnepal
...
h>
#include
...
csitnepal
...
h>
#include
...
5) ? 1 : 0;
}
};
class professor : public person
{
private:
int numpubs;
public:
void getData()
{
person :: getName();
cout<<"\nEnter number of publications";
cin>>numpubs;
}
int isOutstanding()
{
return (numpubs > 100)?1 : 0;
}
};
main()
{
person *persptr[100];
int n = 0;
char choice;
do
{
cout<<"\nEnter student or professor(s/p)";
cin>>choice;
if(choice == 's')
persptr[n] = new student;
else
persptr[n] = new professor;
persptr[n++]->getData();
cout<<"\nAnother record? ";
cin>>choice;
}while(choice == 'y');
for(int j = 0;j < n; j++)
{
persptr[j]->putName();
if(persptr[j]->isOutstanding())
cout<<"\nThis person is outstanding";
}
getch();
return 0;
}
Friend class
The member functions of a class can all be made friends at the same time when we make
the entire class a friend
...
ep
a
itn
Page 94
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
h>
class alpha
{
int data;
public:
alpha()
{
data = 10;
}
friend class beta; // beta is friend class
};
class beta
{
public:
void func1(alpha a)
{
cout<
...
data;
}
};
main()
{
alpha a;
beta b;
b
...
func2(a);
getch();
return 0;
}
In class alpha the entire class beta is defined as a friend
...
The this Pointer
The member functions of every object have access to a sort of magic pointer named this,
which points to the object itself
...
csitnepal
...
h>
#include
...
TestThisPointer();
m2
...
The this pointer can be treated like any
other pointer to an object, and can thus be used to access the data in the object it points
to
...
test();
getch();
return 0;
}
This program simply prints the value 10
...
csitnepal
...
class alpha
{
int data;
l
This is exactly the same as referring to x directly
...
data;
return *this;
}
};
main()
{
alpha a1(50);
alpha a2;
a2 = a1; // calls overloaded operator =
a1
...
display();
getch();
return 0;
}
ep
a
itn
Page 97
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//using this pointer for returning value from member function
class Distance
{
int meter;
int centimeter;
public:
Distance()
{
meter = 0;
centimeter = 0;
}
Distance (int m, int cm)
{
meter = m;
centimeter = cm;
}
void getDist()
{
cout<<"Enter meter";
cin>>meter;
cout<<"Enter centimeter";
cin>>centimeter;
}
void show()
{
cout< }
Distance compare(Distance);
itn
Page 98
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
};
Distance Distance :: compare(Distance d2)
{
float dist1 = meter + (float)centimeter/100;
float dist2 = d2
...
centimeter/100;
if(dist1 < dist2)
return *this;
else
return d2;
}
main()
{
Distance d1(4,50);
Distance d2,d3,d4;
d2
...
compare(d2);
cout<<"Small lenght is: ";
d4
...
Programs can
be designed to perform the read and write operations on these files
...
Data transfer between the console unit and the program
...
Data transfer between the program and a disk file
...
It uses file streams as an interface between the programs and the
files
...
In other words, the input
stream extracts (or reads) data from the file and the output stream inserts (or writes) data
to the file
...
csitnepal
...
Similarly, the output operation involves establishing an output
stream with the necessary links with the program and the output file
...
These include ifstream, ofstream and fstream
...
These classes, designed to
manage the disk files, are declared in fstream and therefore we must include this file in
any program that uses files
...
stream classes for file I/O operations
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files
...
A file stream can be
defined using the classes ifstream, ofstream, and fstream
...
A
file can be opened in two ways
Opening Files Using Constructor
Opening a file using constructor involves the following steps:
itn
Page 100
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
1
...
Using the member function open() of the class
1
...
That is
to say, the class ofstream is used to create the output stream and the class
ifstream to create the input stream
...
Initialize the file object with the desired filename
...
h>
#include
...
h>
void main()
{
char name[20];
int age;
char sec;
ofstream ofile("Student
...
close();
ifstream ifile("student
...
close();
getch();
}
When a file is opened for writing only, a new file is created if there is no file of that
name
...
Opening Files Using open()
The function open() can be used to open multiple files that use the same stream object
...
This
is done as
file-stream-class
stream-object;
stream-object
...
csitnepal
...
h>
#include
...
h>
main()
{
char name[20];
int age,salary;
char sec;
ofstream ofile;
ofile
...
txt");
cout<<"\nEnter name, age section: ";
cin>>name>>age>>sec;
ofile< ofile< ofile< ofile
...
open("teacher
...
close();
getch();
}
File Modes with open()
The open function can take two arguments, the second one for specifying the file mode
...
open(“filename”, mode);
The second argument (called file mode parameter) specifies the purpose for which the
file is opened
...
ep
a
itn
Page 102
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
put() and get() Functions
The function put() writes a single character to the associated stream
...
#include
...
h>
#include
...
open("myfile
...
get(ch);
while(ch != '\n')
{
file
...
get(ch);
}
file
...
open("myfile
...
get(ch);
cout< }
file
...
This means that the values are stored in the disk file in the same format in
which they are stored in the internal memory
...
But a 4 digit int will take four
bytes to store it in the character form
...
The first is the address of the variable, and the second is the length of that variable in
bytes
...
ep
a
itn
Page 103
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//writing array of integers using write()
#include
...
h>
#include
...
open("myfile
...
write((char*)&x,sizeof(x));
file
...
open("myfile
...
read((char*)&x,sizeof(x));
for(i = 0;i < 4;i++)
cout< getch();
}
Writing and Reading Class Objects (Object I/O)
When writing an object we generally want to use binary mode
...
The binary input output functions
write() and read() are used for this
...
h>
#include
...
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
{
cin>>name>>age;
}
void showData()
{
cout< }
};
main()
{
ep
a
itn
Page 104
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
person p,q;
fstream file;
file
...
dat",ios::out|ios::binary);
cout<<"\nEnter person's data: ";
p
...
write((char *)(&p),sizeof(p));
file
...
open("person
...
read((char *)(&q),sizeof(q));
q
...
csitnepal
...
h>
#include
...
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
{
cin>>name>>age;
}
void showData()
{
cout< }
};
main()
{
char ch;
person p;
fstream file;
file
...
dat",ios::out|ios::in|ios::binary);
do
{
cout<<"\nEnter person's data: ";
p
...
write((char *)(&p),sizeof(p));
cout<<"Enter another person? ";
cin>>ch;
}while(ch == 'y');
file
...
read((char *)(&p),sizeof(p));
while(!file
...
showData();
file
...
These are also called the current get position and the current put position, or
simply the current position
...
The seekg() and tellg() functions allow us to set and
examine the get pointer, and the seekp() and tellp() functions perform these same actions
on the put pointer
...
The argument
to these functions represents the absolute position in the file
...
The refposition takes one of the
following three constants defined in the class ios
ios :: beg
ios :: cur
ios :: end
start of file
current position of the pointer
end of the file
...
If file is an object of ofstream, then some some
sample pointer offset calls and their actions are:
Action
go to start
stay at the current position
go to the end of file
...
csitnepal
...
h>
ep
a
Seek call
file
...
seekg(0,ios::cur);
file
...
seekg(m,ios::beg);
file
...
csitnepal
...
h>
#include
...
open("group
...
seekg(0,ios::end);
int endposition = file
...
seekg(pos);
file
...
showData();
cout<<"\nRecords in file are:\n";
file
...
read((char*)&p,sizeof(p));
while(!file
...
showData();
file
...
close();
getch();
return 0;
}
// File copy program
...
#include
...
h>
#include
...
h>
void main()
{
char ch;
fstream file1,file2;
file1
...
txt",ios::out|ios::in);
file1<<"welcome to object oriented programming";
file1
...
open("test1
...
open("test2
...
get(ch);
ch = toupper(ch);
file2
...
close();
file2
...
open("test2
...
get(ch);
cout< }
file2
...
Some functions are
good()
returns true if end of file is encountered while reading, otherwise return
returns true when an input or output operation has failed
...
returns true if no error has occurred
...
csitnepal
...
h>
#include
...
fail()
bad()
#include
...
open("myfile
...
fail())
{
cout<<"\nCould not open the file";
}
else
{
while(file)
{
file
...
close();
}
getch();
}
ep
a
itn
Page 109
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
h>
#include
...
open("myfile
...
good())
{
cout<<"\nCould not open the file";
}
else
{
while(file)
{
file
...
close();
}
getch();
}
Namespace
Namespaces allow to group entities like classes, objects and functions under a name
...
The
format
of
namespaces
is:
namespace
{
entities
}
identifier
Where identifier is any valid identifier and entities is the set of classes, objects and
functions that are included within the namespace
...
In order to access these variables from outside the
”myNamespace” namespace we have to use the scope operator ::
...
csitnepal
...
1416;
}
int main () {
cout << first::var << endl;
cout << second::var << endl;
return 0;
}
In this case, there are two global variables with the same name: var
...
No redefinition errors happen thanks to
namespaces
...
Example program2
#include
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
namespace second
{
double x = 3
...
7183;
}
itn
Page 111
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
int main () {
using namespace first
cout << x << endl;
cout << y << endl;
using namespace second
cout< cout< return 0;
}
Templates
(Meaning to word: A document or file or entity having a preset format, used as a
starting point for a particular application so that the format does not have to be recreated
each time it is used)
A template is one of the recently added feature in c++
...
Generic programming is an approach where generic data types
are used as parameters in algorithms so that they can work for a variety of suitable data
types
...
This allows a function or class to work on many
different data types without being rewritten for each one
...
Note that the
type is the only "parameter" of a template, but a very powerful one, since anything from a
function to a class (or a routine) can be specified in "general" terms without concerning
yourself about the specific type
...
csitnepal
...
You create only one generic version of your class or
function instead of manually creating specializations
...
Templates are typesafe
...
Templates and Macros
In many ways, templates work like preprocessor macros, replacing the templated variable
with the given type
...
The macro is expanded without any special type checking
...
For example, if either parameter has a
post incremented variable, the increment is performed two times
...
Also, the
macro will show up in expanded form during debugging
...
An individual class defines how a group of
objects can be constructed, while a class template defines how a group of classes can be
generated
...
h>
ep
a
itn
Page 113
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
template
class vec {
T x;
T y;
public:
vec(T f1, T f2)
{
x=f1;
y=f2;
}
vec()
{ }
vec operator+(const vec& v1)
{
vec result;
result
...
x+this->x;
result
...
y+this->y;
return result;
}
};
int main() {
vec v1(3,6);
vec v2(2,-2);
vec v3=v1+v2;
vec v4(3
...
7);
vec v5(2
...
2);
vec v6=v4+v5;
}
Advantages of C++ Class Templates:
Function template
itn
Page 114
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
One C++ Class Template can handle different types of parameters
...
If the template is instantiated
for int type, compiler generates only an int version for the c++ template class
...
Testing and debugging efforts are reduced
...
we can write a single function template definition
...
Syntax:
The general form of a function template is
Template
returnType function_name (argument of type T)
{
//body of function with type T whenever appropriate
}
Using Template Functions: example
Using function templates is very easy: just use them like regular functions
...
Similarly the compiler
generates definitions for max(char, char) and max(float, float) in this case
...
1, 15
...
1, 15
...
csitnepal
...
1, 15
...
2
itn
Page 116
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
The template keyword signals the compiler that I’m about to define a function template
...
As
you’ve seen, you can define your own data types using classes, so there’s really no
distinction between types and classes
...
Classes and Objects
One of the unique facilities provided by C language is “structure”
...
It was termed as a user defined data-type
...
Eg
...
- They don’t allow data hiding
...
- C does not allow the structure data type to be treated like built in data type
...
But C++ has expanded its
capabilities further to suit its OOP philosophy
...
In C++, a structure can have both variables and functions as members
...
In C++, the structure names are stand-alone and can be used like any other
type names
...
C++ incorporates all these extensions in another user-defined type known as class
...
Since class is a specially
introduced data type in C++, most of the C++ programmers tend to use the structure for
holding only data, and classes to hold both the data and functions
...
ep
a
itn
Page 117
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Class is a collection of logically related data items and the associated functions which
operate and manipulate those data
...
So, classes are user-defined data types and behave like the built-in types of a
programming language
...
Class,
being a user-defined data type, we can create any number of variables for that class
...
Specifying a class
Specification of a class consists of two parts
...
The class-name is an identifier
...
The functions and variables are collectively called class-members
...
The two new keywords inside the above specification are – private and public
...
These are followed by colons
...
i
...
, only the member functions can have access
to the private data members and private functions
...
Private data members and
function
itn
Page 118
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
o All the class members are private by default
...
l
Public data members and
functions
o If both the labels are missing, then, by default, all the members will be
private and the class will be completely inaccessible by the outsiders
(hence it won’t be useful at all)
...
Generally, data within a class is made private and
the functions are public
...
However, it is not always necessary that
the data must be private and functions public
...
Example of a class
itn
Page 119
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Creating Objects
Once a class has been specified (or declared), we can create variables of that type (by
using the class name as datatype)
...
The above statement creates a variable t1 of type Test
...
So, t1 is called object of class Test
...
Test t1, t2, t3;
When object is created, the necessary memory space is allocated to this object
...
Objects can be
created when a class is defined, as follows:
class Employee
{
int id;
char name[20];
public:
void getname();
void putname();
}e1,e2,e3;
The objects are also called instances of the class
...
l
class Test
{
int x,y;
public:
void get_data()
{
cin>>x>>y;
}
void put_data()
{
cout< }
};
Accessing class members
The class members are accessed using a dot operator
...
The dot operator is called member access operator
...
class-member ;
For public data members (if any), we can use following syntax to access them
...
data-member ;
eg
...
data1 = obj1
...
data3;
In the above example, obj1 is an object of class
...
For public functions, we can use following format to call them
class-object
...
e1
...
Here, no arguments have been listed since the function does not take any argument
...
Eg
...
x = 0; //generates error since x is private and can be accessed only thro’
member functions
obj1
...
fu1(); //generates error since fu1() is private
obj1
...
csitnepal
...
o outside the class
o inside the class
The code for the function body would be identical in both the cases
...
l
Defining member functions (i
...
writing the body of a function):
Outside the class
In this approach, the member functions are only declared inside the class, whereas its
definition is written outside the class
...
General form:
return-type class-name::function-name(argument-list)
{
--------- - - - - - - -- - //function body
- - - -- - -- -}
The function is, generally, defined immediately after the class-specifier
...
This symbol is called the scope resolution
operator
...
Eg
...
The scope-resolution operator tells that the function “getdata()” is a
member of the class “Employee”
...
itn
Page 121
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Inside the class
Function body can be included in the class itself by replacing function declaration by
function definition
...
Hence, all
the restrictions that apply to inline function, will also apply here
...
These classes can use same
function name
...
- Member functions can directly access private data of that class
...
(Exception is friend function)
- A member function can call another member function directly, without using
the dot operator
...
class A
{
int a,b;
public:
void getdata()
{
cin>>a>>b;
}
};
Here, getdata() is defined inside the class
...
A function defined outside the class can also be made ‘inline’ simply by using the
qualifier ‘inline’ in the header line of a function definition
...
class A
{
----- ------------ public:
void getdata(); // function declaration inside the class
};
inline void A::getdata()
{
//function body
}
Function definition with the ‘inline’
qualifier/keyword
...
However, a member function can be called by using its name inside another member
function of the same class
...
Eg
...
h>
ep
a
itn
Page 122
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
class Addition
{
int a,b,sum;
public:
void read();
void show();
int add();
};
void Addition::read()
{
cout<<”Enter a and b”;
cin>>a>>b;
}
void Addition::add()
{
return(a+b);
}
void Addition::show()
{
sum=add(); // nesting of function i
...
cout< }
main()
{
Addition a1;
a1
...
show( );
return(0);
}
The output of this program will be as follows:
Enter a and b: 2
3
Sum of a and b is:5
Private Member Functions
As we have seen, member functions are, in general, made public
...
Private member functions
can only be called by another function that is a member of its class
...
Eg
...
csitnepal
...
No object used
...
a1
...
Memory Allocation for Objects
- As in the case of structures, memory space for objects is allocated when they
are declared and not when the class is specified
...
The member functions are created and placed
in the memory only once, when they are defined as a part of a class
specification
...
- However, the data members will hold different values for different object
...
Object1
Object2
Object3
datamember1
datamember2
…
...
datamemberN
datamember1
datamember2
…
...
csitnepal
...
...
Since a class is also a user defined data type, we
can create array of objects (the variable of type class)
...
For eg
...
If we have to
keep records of 20 employees in an organization having two departments, then instead of
creating 20 separate variables, we can create array of objects as follows
...
Since the array of objects is an array, we can access the members of the classes as
follows:
dept1[0]
...
getdata();
Objects as function arguments
Like any other variable, objects can also be passed to the function, as an argument
...
- pass by value
- pass by reference
In the “pass by value”, the copy of the object is passed to the function
...
On the other hand,
address of the object is passed in the case of pass by reference
...
The second method is
considered more efficient
...
csitnepal
...
class Height
{
int feet;
int inches;
public:
void getHeight()
{
cout<<”Enter height in feet and inches”;
cin>>feet>>inches;
}
void putHeight()
{
cout<<”Feet:”< cout<<” and Inches:”< }
void sum(Height,Height);
};
void Height::sum(Height h1, Height h2)
{
inches = h1
...
inches;
feet=inches/12;
inches=inches%12;
feet=feet + h1
...
feet;
}
int main()
{
Height h1,h2,h3;
h1
...
getHeight();
h3
...
putHeight();
cout<<”Height 2:”<
...
putHeight();
return(0);
}
In the above program, the function sum() takes two objects as arguments
...
Eg
...
csitnepal
...
inches = h1
...
inches;
h3
...
inches / 12;
h3
...
inches % 12;
h3
...
feet + h1
...
feet;
return (h3); //object of type height returned
}
The above function will return an object h3 at the end of its execution
...
In other words, a friend function is a non-member function that has access to the private
members of the class
...
- Since, friend function is not a part of the class, it can be declared anywhere in
the public, private and protected section of the class
...
- It is called like a normal function without the help of any object
...
So, it has
to use an object name and dot operator with each member name (like A
...
A friend function is declared as follows:
class A
{
- - - - - - - - - - -- - - - - - - - - - - - - - - -- - - - - public:
----------------------------------friend void abc(void);
};
//friend function declaration
The declaration is preceded by the keyword “friend”
...
Eg
...
csitnepal
...
n1 + a
...
getn();
cout<<”Mean:”< //friend function called
return(0);
}
Suppose we want a function to operate on objects of two different classes
...
In this situation there is nothing like a friend function
...
Read program
carefully!!!!!!!!
#include
...
h>
class beta; // needed for frenfunction declaration
ep
a
itn
Page 128
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
class alpha
{
private:
int data;
public:
void get_data()
{
cin>>data;
}
friend int frenfunction(alpha, beta); // friend function
};
class beta
{
private:
int data;
public:
void get_data()
{
cin>>data;
}
friend int frenfunction(alpha, beta); // friend function
};
int frenfunction(alpha a,beta b)
{
return(a
...
data);
}
main()
{
alpha aa;
beta bb;
aa
...
get_data();
cout< getch();
return 0;
}
Static Data Members
We have known that, each object of a class maintain their own copy of member data
...
This can be made possible by using static variables
...
- It is visible only within the class, but its lifetime is the entire program
...
- Also known as class variable
...
class A
{
ep
a
itn
Page 129
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
static int count;
int variable;
public:
A()
{
count++;
}
void get_var()
{
cin>>variable;
}
void put_var()
{
cout< }
definition
...
{
cout<
...
};
int A::count;
int A::count=10;
will assign count the initial value 10
main()
{
A a,b,c;
a
...
put_count();
c
...
Properties of static functions are
- they can access only other STATIC members (functions or variables) declared
in the same class
- they can be called using class name
eg
...
csitnepal
...
is :”< }
static void put_count()
//static function accessing static member
{
cout< }
};
int A::count;
main()
{
A a1,a2;
a1
...
set_no();
A::put_count();
a1
...
set_no();
A::put_count();
a1
...
put_no();
return(0);
}
itn
Page 131
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Check output of this program
...
In all the cases, we
have used member functions such as input() and output() to provide initial values to the
private member variables
...
input();
invokes the member function input(), which assigns the initial values to the data items of
object t
...
input(100,200);
passes the initial values as arguments to the function input(), where these values are
assigned to the private variables of object t
...
These functions can not be
used to initialize the member variables at the time of creation of their objects
...
This means that we should be able to initialize a class type
variable (object) when it is declared, much the same way as initialization of an ordinary
variable
...
67;
are valid initialization statements for basic data types
...
But it has not happened with the objects we have so far studied
...
C++ provides a special member function called the constructor which enables an object
to initialize itself when it is created
...
It also provides another member function called the destructor that destroys the objects
when they are no longer required
...
It has the name same as that of class name
...
It is called constructor because it constructs the
values of data members of the class
...
csitnepal
...
They execute automatically when an object of a class is created
...
They should be declared in the “public” section
...
Like C++ functions, they can have default arguments
...
There are, basically, three types of constructors
...
There are
three possible situations for this
...
If we do not provide any constructor with a class, the compiler provided one
would be the default constructor
...
class A
{
//no constructor
};
5
...
class A
{
A()
{}
//or
A(void)
{}
};
Parameterized Constructor
itn
Page 133
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
6
...
class A
{
A (int x=5)
{}
};
A constructor that takes arguments is called a parameterized constructor
...
This can be done in two ways
...
class A
{
int m,n;
public:
A(int x, int y); //parameterized constructor
{
m=x;
n=y;
}
-
-
};
main()
{
Class name
Object name
A obj1(10,20); //implicit call
A obj2 =A(10,20); //explicit call
Constructor call with parameter
-
-
-
}
NOTE: Constructor functions can also be defined explicitly using scope resolution
operator
...
Eg
...
The above statement can also be written as,
itn
Page 134
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
The process of initializing through a copy constructor is known as copy initialization
...
We cannot pass the argument by value to a copy constructor
...
Remember the
statement
obj2 = obj1;
will not invoke the copy constructor
...
This is the task of the overloaded assignment operator (=)
...
class Data
{
int info;
public:
Data()
{}
Data(int a)
// parameterized constructor
{
info
}
Data(Data &x) // copy constructor
{
info=x
...
Data d2(d1); //copy constructor is called here
...
Data d4;
d4 = d1; // copy constructor not called
cout<<”An info stored in d1”;
d1
...
display();
itn
Page 135
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
d3
...
display();
return(0);
}
Constructors are called thrice in this program
...
Similarly, when more than one constructor is defined in a class, it is called
constructor overloading
...
The first one is
invoked when we don’t pass any arguments
...
Eg
...
Data obj2(5); invokes 2nd constructor
Data obj3(obj2); invokes 3rd constructor
Constructor with default argument
Like functions, constructors can also have default arguments
...
class A
{
int a,b,c;
pulic:
A()
{
a=0
}
A(int x,int y=10,int z=20)
{
a=x;b=y;c=z;
}
void display()
{
cout<};
itn
Page 136
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
}
main()
{
A obj1;
A obj2(5,10,15);
A obj3(6);
obj1
...
display();
obj3
...
The second one has default parameters
...
These constructors have all
the properties of the functions with default argument
...
The default argument constructor can be called
with either one argument or no arguments
...
When both these forms are used in a class, it causes ambiguity for a
statement such as
A a;
The ambiguity is whether to call A::A() or A::A(int x = 0)
...
csitnepal
...
h>
#include
...
display();
test t1;
// No argument is passed, so becomes default constructor
t1
...
e
...
The users provide the
values at the run time
...
Eg
...
And we haven’t used the object
l=a;and dot operator
...
csitnepal
...
In other words, they are used to release dynamically allocated memory and
to perform other “cleanup” activities
...
Eg
...
e
...
They are also defined in the public section
...
So, they cannot be overloaded
...
h>
#include
...
csitnepal
...
Programs can
be designed to perform the read and write operations on these files
...
Data transfer between the console unit and the program
...
Data transfer between the program and a disk file
...
It uses file streams as an interface between the programs and the
files
...
In other words, the input
stream extracts (or reads) data from the file and the output stream inserts (or writes) data
to the file
...
Similarly, the output operation involves establishing an output
stream with the necessary links with the program and the output file
...
csitnepal
...
These include ifstream, ofstream and fstream
...
These classes, designed to
manage the disk files, are declared in fstream and therefore we must include this file in
any program that uses files
...
stream classes for file I/O operations
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files
...
A file stream can be
defined using the classes ifstream, ofstream, and fstream
...
A
file can be opened in two ways
3
...
Using the member function open() of the class
Opening Files Using Constructor
Opening a file using constructor involves the following steps:
Page 141
itn
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
ofstream file(“student”); //write only
ifstream file(“employee”); // read only
cs
For example:
l
3
...
That is
to say, the class ofstream is used to create the output stream and the class
ifstream to create the input stream
...
Initialize the file object with the desired filename
...
h>
#include
...
h>
void main()
{
char name[20];
int age;
char sec;
ofstream ofile("Student
...
close();
ifstream ifile("student
...
close();
getch();
}
When a file is opened for writing only, a new file is created if there is no file of that
name
...
Opening Files Using open()
The function open() can be used to open multiple files that use the same stream object
...
This
is done as
file-stream-class
stream-object;
stream-object
...
csitnepal
...
h>
#include
...
h>
main()
{
char name[20];
int age,salary;
char sec;
ofstream ofile;
ofile
...
txt");
cout<<"\nEnter name, age section: ";
cin>>name>>age>>sec;
ofile< ofile< ofile< ofile
...
open("teacher
...
close();
getch();
}
File Modes with open()
The open function can take two arguments, the second one for specifying the file mode
...
open(“filename”, mode);
The second argument (called file mode parameter) specifies the purpose for which the
file is opened
...
put() and get() Functions
The function put() writes a single character to the associated stream
...
ep
a
itn
Page 143
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
h>
#include
...
open("myfile
...
get(ch);
while(ch != '\n')
{
file
...
get(ch);
}
file
...
open("myfile
...
get(ch);
cout< }
file
...
This means that the values are stored in the disk file in the same format in
which they are stored in the internal memory
...
But a 4 digit int will take four
bytes to store it in the character form
...
The first is the address of the variable, and the second is the length of that variable in
bytes
...
ep
a
itn
Page 144
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//writing array of integers using write()
#include
...
h>
#include
...
open("myfile
...
write((char*)&x,sizeof(x));
file
...
open("myfile
...
read((char*)&x,sizeof(x));
for(i = 0;i < 4;i++)
cout<
getch();
}
Writing and Reading Class Objects (Object I/O)
When writing an object we generally want to use binary mode
...
The binary input output functions
write() and read() are used for this
...
h>
#include
...
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
{
cin>>name>>age;
}
void showData()
{
cout< }
};
main()
{
person p,q;
fstream file;
file
...
dat",ios::out|ios::binary);
cout<<"\nEnter person's data: ";
p
...
write((char *)(&p),sizeof(p));
file
...
open("person
...
read((char *)(&q),sizeof(q));
q
...
csitnepal
...
csitnepal
...
h>
#include
...
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
{
cin>>name>>age;
}
void showData()
{
cout< }
};
main()
{
char ch;
person p;
fstream file;
file
...
dat",ios::out|ios::in|ios::binary);
do
{
cout<<"\nEnter person's data: ";
p
...
write((char *)(&p),sizeof(p));
cout<<"Enter another person? ";
cin>>ch;
}while(ch == 'y');
file
...
read((char *)(&p),sizeof(p));
while(!file
...
showData();
file
...
These are also called the current get position and the current put position, or
simply the current position
...
The seekg() and tellg() functions allow us to set and
examine the get pointer, and the seekp() and tellp() functions perform these same actions
on the put pointer
...
The argument
to these functions represents the absolute position in the file
...
The refposition takes one of the
following three constants defined in the class ios
ios :: beg
ios :: cur
ios :: end
start of file
current position of the pointer
end of the file
...
If file is an object of ofstream, then some some
sample pointer offset calls and their actions are:
Action
go to start
stay at the current position
go to the end of file
...
csitnepal
...
h>
#include
...
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
ep
a
Seek call
file
...
seekg(0,ios::cur);
file
...
seekg(m,ios::beg);
file
...
open("group
...
seekg(0,ios::end);
int endposition = file
...
seekg(pos);
file
...
showData();
cout<<"\nRecords in file are:\n";
file
...
read((char*)&p,sizeof(p));
while(!file
...
showData();
file
...
close();
getch();
return 0;
}
ep
a
itn
Page 148
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
// File copy program
...
#include
...
h>
#include
...
h>
void main()
{
char ch;
fstream file1,file2;
file1
...
txt",ios::out|ios::in);
file1<<"welcome to object oriented programming";
file1
...
open("test1
...
open("test2
...
get(ch);
ch = toupper(ch);
file2
...
close();
file2
...
open("test2
...
get(ch);
cout< }
file2
...
Some functions are
good()
returns true if end of file is encountered while reading, otherwise return
returns true when an input or output operation has failed
...
returns true if no error has occurred
...
csitnepal
...
h>
#include
...
h>
void main()
{
char ch;
fstream file;
file
...
txt",ios::in); // read only
if(file
...
fail()
bad()
}
else
{
while(file)
{
file
...
close();
}
getch();
}
itn
Page 150
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
#include
...
h>
#include
...
open("myfile
...
good())
{
cout<<"\nCould not open the file";
}
else
{
while(file)
{
file
...
close();
}
getch();
}
Functions
A function is a single comprehensive unit that performs a specified task
...
Functions break large programs into
smaller tasks
...
Like in C, C++ programs also should contain a main function, where the program always
begins execution
...
When a function is called, control is transferred to the first statement of the function
body
...
Function Prototype (Function declaration)
Function prototype lets the compiler know the structure of function in terms of its name,
number and type of arguments and its return type
...
We call a function as follows
...
,argument n);
Function Definition
Function definition is a process of defining how it does what it does or in other words,
during function definition, we list the series of codes that carry out the task of the
function
...
, datatype n var n)
{
……………… ;
…………………
...
;
}
Default Arguments
In C++, a function can be called without specifying all its arguments
...
The function declaration must provide default values for
those arguments that are not specified
...
ep
a
itn
Page 151
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
0);
main()
{
float rate, i1,i2,i3;
int pr , yr;
cout<<”Enter principal, rate and year”;
cin>>pr>>rate>>yr;
i1=interest(pr ,yr ,rate);
i2=interest(pr , yr);
i3=interest(pr);
cout< return(0);
}
float interest(int p, int t, float r)
{
return((p*t*r)/100);
}
In the above program, t and r has default arguments
...
Only the trailing arguments can have default values
...
We cannot provide a default value to a particular argument at the middle of an
argument list
...
For eg
...
Inline Functions
itn
Page 152
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
C++ has a solution for this problem
...
When a function is defined as inline, compiler copies it s body where the function call is
made, instead of transferring control to that function
...
Eg
...
However, every time a function
is called, it takes a lot of extra time in executing a series of instructions
...
When a
function is small, considerable amount of time is spent in such overheads
...
The compiler may not always accept this request
...
Eg
...
h>
inline float lbtokg(float lbs)
{
return (0
...
When do we use default argument? Explain with example
...
csitnepal
...
i
...
function overloading is the process of using the
same name for two or more functions
...
The number, type or sequence of parameters for a function is called the
function signature
...
Two functions differing only in their return type can not be
overloaded
...
A best match must be
unique
...
#include
...
0)< cout<<”Perimeter of a rectangle: ”< cout<<”Perimeter of a triangle: ”< return (0);
}
ep
a
itn
Page 154
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//function definition
float perimeter(float r)
{
return(2*3
...
The output will be as
follows:
Perimeter of a circle 12
...
It defines
the problem in terms of itself
...
so that the smaller problem is easy to solve
and in the most case they can be solved easily
...
C++ support
such function and these function are called recursive functions
For example: to find the factorial of a given number
Int mani()
{
int num;
cout<<”Enter a number”;
cin>>num;
int f=fact(num);
cout>>”the factorial of given number is”< getch();
return 0;
}
itn
Page 155
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
int fact(int num)
{
If(num==0)
Return 1;
Else
Return (num*fact(num-1));
}
Inheritance
Inheritance is the most powerful feature of object-oriented programming
...
The class inherits all the capabilities of the base class but can add refinements of
its own
...
Inheritance is also called a ‘kind of relationship’
...
Once a class has been written and tested, its features can be adapted by
other programmers whenever required
...
Inheritance
itn
Page 156
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Types
There are 5 types of inheritance
1) Single Inheritance – when a class is derived from only one base class, then it is called
single inheritance
...
// body part
…
}
public:
{
…
...
}
};
class B : public A // derived class B
{
……
…
...
It can be represented as,
Base class A
Base class B
itn
Page 157
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Derived class C
Egclass A
{
……
...
……
};
class C : public A, public B
{
……
...
3) Hierarchical Inheritance: When two or more than two classes are derived from one
base class, it is called hierarchical inheritance
...
csitnepal
...
………
...
……
};
class C : public A
{
………
ep
a
B
………
};
Here two classes B and C are derived from same base class A
...
g
...
…
...
……
};
class C : public B
{
…
...
};
In this example class B is derived from base class A and class C is derived from derived
class B
...
csitnepal
...
gclass student
{
……
…
...
……
...
};
class result : public test, public sport
{
……
…
...
The class test and sport are derived from
student and class result is derived from both test and sport classes
...
itn
Page 160
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Sub-class Definition
A subclass can be defined by specifying its relationship with base class along with its
own details
...
………
};
baseclass-name
The colon indicates that the inheritance has been used
...
e
...
The visibility mode specifies whether the features of the base class are
derived privately, publicly or protectedly
...
The three visibility modes are
public
private
protected
When the base class is publicly inherited, all the public members of the base class
become public members of the derived class
...
All the protected members become protected members of the
derived class
...
So, these can not be accessed
outside the class directly through the derived class object, but might be accessed through
public functions in the derived class
...
NOTE: private members can not be inherited at all
...
When a member is defined with protected access specifier, these members can be
accessed from that class and also from the derived class of this base class
...
i
...
protected members act as public for
derived class and private for other classes
...
csitnepal
...
Consider the program
#include
...
This means, like a
private inheritance, these members can not be directly accessed through object of the
derived class
...
Whereas, unlike a private
inheritance, they can still be inherited and accessed by subsequent derived classes
...
class aclass
{
public:
void disp(void)
{
cout<<”Base”< }
};
class bclass : public aclass
{
public:
void disp(void)
{
cout<<”Derived”< }
};
void main()
{
bclass Bvar;
Bvar
...
If the function is invoked from an object of the derived class, then the function in
the derived is executed
...
Ambiguities in Multiple Inheritance
When a class inherits from multiple base classes, a whole part of ambiguities creep in
...
csitnepal
...
h>
class base1
{
public:
void disp(void)
{
cout<<”Base1”< }
};
class base2
{
public:
void disp(void)
{
cout<<”Base2”< }
itn
Page 163
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Here, the reference to disp() is ambiguous because the compiler does not know whether
disp() refers to the member in class base1 or base2
...
base1::disp();
Dvar
...
That is, the members can be
redefined in the derived class
...
};
class derived : public base1, public base2
{
public:
void disp(void)
{
base1::disp();
base2::disp();
cout<<”Derived class”< }
};
void main()
{
derived Dvar;
Dvar
...
disp(); // Ambiguous
}
}
Another ambiguity that arises in multiple inheritance is the possibility of the derived class
having multiple copies of the same base class
...
B and C in
turn are derived from class A
...
There are two ways of resolving this ambiguity
...
Containership
When a class contains object of another class as its member data, it is termed as
containership
...
Containership
is also termed as “class within class”
...
A obj1;
…
...
So
B is the container class
...
csitnepal
...
Containership is useful with classes that act like a data type
...
l
‘containership’ is also called ‘has-a’ relationship
...
This is
because B has all the characteristics of A, and in addition some of its own
...
itn
Page 165
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
class Manager
{
char name[20];
int age;
public:
void getdata()
{
cin>>name>>age;
}
void putdata()
{
cout< }
};
class Employee // Employee is container class
{
char department[20];
Manager m; // Object of class Manager
public:
void getdata()
{
m
...
putdata();
cout< }
};
void main()
{
Employee e;
e
...
putdata();
getch();
}
Abstract Class
An abstract class is one that is not used to create objects
...
It is a design concept in program development and provides a
base upon which other classes may be built
...
When the same class is
inherited more than once via multiple paths, multiple copies of the base class members
are created in memory
...
A base class inheritance can be specified as a virtual using
the virtual qualifier
...
…
...
…
...
};
class C : public B1, public B2
{
……
……
};
Keywords ‘virtual’ and ‘public’ can be used in either way
...
csitnepal
...
However, if any base
class contains a constructor with one or more arguments, then it is mandatory for the
derived class to have a constructor and pass the arguments to the base class constructors
...
Thus, it
makes sense for the derived class to pass arguments to the base class constructor
...
Since there is only one copy, there is no ambiguity
...
Since the derived class takes the responsibility of supplying initial values to its base
classes, we supply the initial values that are required by all the classes together, when a
derived class object is declared
...
The constructor of the derived class receives the entire list of values as its arguments and
passes them onto the base constructors in the order in which they are declared in the
derived class
...
Example-
ep
a
itn
Page 167
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
5,50,60);
g
...
show_y();
g
...
Since the derived class contains more than one
Constructors and/or Destructors, it becomes confusing which one will be called when
...
This article will clear all this!
Consider the following example program:
// -- INHERITANCE -// Constructors, Destructors
// and Inheritance
#include
...
csitnepal
...
One more example will clear the confusions, if any
...
h>
ep
a
itn
Page 169
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
// base class (1)
class base
{
public:
base(){cout<<"Constructing Base\n";}
~base(){cout<<"Destructing Base\n";}
};
// derived class
// derived form 'base'
class derived1:public base
{
public:
derived1(){cout<<"Constructing Derived1\n";}
~derived1(){cout<<"Destructing Derived1\n";}
};
// derived from a derived class
// 'derived1'
class derived2:public derived1
{
public:
derived2(){cout<<"Constructing Derived2\n";}
~derived2(){cout<<"Destructing Derived2\n";}
};
void main(void)
{
derived2 obj;
// do nothing else, only
// construct and destruct
// the inherited class object
}
OUTPUT:
Constructing Base
Constructing Derived1
Constructing Derived2
Destructing Derived2
Destructing Derived1
Destructing Base
itn
Page 170
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Lab Sheet - 3
Employee
Name
ID
getdata()
putdata()
Manager
ComputerOperator
Department
Typing_Speed
getdata()
putdata()
getdata()
putdata()
7
...
Also write a
main() function to test the classes, Manager and ComputerOperator, by creating
their objects, taking input and displaying the corresponding values
...
Imagine a college hires some lecturers
...
Create a class called lecturer that stores the
ID, and the name of lecturers
...
Each of these three classes should have a readdata() function to get its
data from the user, and a printdata() function to display its data
...
9
...
Create a class Automobile that stores production
date and price
...
Each
of these classes should have member functions to get data and set data
...
itn
Page 171
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
10
...
From this class derive two classes: Bowler and Batsman
...
Use appropriate member functions
in all classes to read and display respective data
...
Define a base class Shape having data member radius (int)
...
Write methods to compute the area of
circle and sphere
...
csitnepal
...
Create classes Book having data members name of author (string), price (float)
and class Stock having data members number of books (int) and category (string)
...
All the classes should have functions having same name
...
Namespace
Namespaces allow to group entities like classes, objects and functions under a name
...
The
format
of
namespaces
is:
namespace
{
entities
}
identifier
Where identifier is any valid identifier and entities is the set of classes, objects and
functions that are included within the namespace
...
In order to access these variables from outside the
”myNamespace” namespace we have to use the scope operator ::
...
1416;
}
ep
a
itn
Page 173
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
int main () {
cout << first::var << endl;
cout << second::var << endl;
return 0;
}
In this case, there are two global variables with the same name: var
...
No redefinition errors happen thanks to
namespaces
...
Example program2
#include
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
namespace second
{
double x = 3
...
7183;
}
itn
Page 174
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
int main () {
using namespace first
cout << x << endl;
cout << y << endl;
using namespace second
cout< cout< return 0;
}
Operator Overloading
The concept of overloading can be applied to operators as well
...
It provides a flexible option for
the operations of new definitions for most of the C++ operators
...
In general,
a = b + c; works only with basic types like ‘int’ and ‘float’, and attempting to
apply it when a, b and c are objects of a user defined class will cause complaints from the
compiler
...
There are two types of operator overloading
Unary operator overloading and
Binary operator overloading
Unary operator overloading
Unary operators are those operators that act on a single operand
...
The following program overloads the ++ unary operator for the distance class
to increment the data number by one
...
csitnepal
...
display();
}
In the above example, the ++ unary operator has been overloaded in the function void
Distance :: operator ++(void)
...
This function is called at the second line ‘++dist’ in the main
...
list)
{
//func body
}
The keyword ‘operator’ is used to overload an operator
...
//Another Example - overloading unary minus operator
class abc
{
int x,y,z;
public:
void getdata(int a,int b,int c)
{
x = a;
y = b;
z = c;
}
void display()
{
cout< }
void operator -();
};
void abc::operator-()
{
x = -x;
y = -y;
z = -z;
}
main()
{
ep
a
itn
Page 176
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
abc a;
a
...
display();
-a;
a
...
If we use a statement like this
c1 = ++c2;
For this we have to define the ++ operator to have a return type object of a class in the
operator++ function
...
the example given
below illustrates this
...
csitnepal
...
put_count();
c2
...
put_count();
c2
...
What about postfix, where the
variable is incremented after its value is used in the expression?
c1++
to make both versions of the increment operator work, we define two overloaded ++
operators as follows
class Counter
{
int count;
public:
Counter()
{
count = 0;
}
Counter(int c)
{
count = c;
}
Counter operator++()
{
return Counter(++count);
}
Counter operator++(int)
{
return Counter(count++);
}
void put_count()
{
cout< }
};
main()
{
ep
a
itn
Page 178
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Counter c1,c2,c3;
c1
...
put_count();
c2 = ++c1;
c3 = c2++;
c1
...
put_count();
c3
...
The one, for
prefix notation, is
Counter operator ++()
The one, for postfix notation, is
Counter operator ++(int)
The only difference is the int in the parentheses
...
It’s simply a signal to the compiler to create the postfix version of
the operator
...
Overloading binary operators
Binary operators are those that work on two operands
...
Overloading a binary operator is similar to overloading unary operator except that a
binary operator requires an additional parameter
...
It adds two objects of type ‘distance’
...
csitnepal
...
meter;
int cm = centimeter + d2
...
getDist();
d3 = d1 + d2; // Invokes operator+() function
d4 = d3
...
show();
d4
...
The argument on the left side the operator (d1 here) is the
object of which the operator is a member
...
Overloading Binary Operators Using Friend Function
ep
a
itn
Page 180
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Friend functions may be used in the place of member functions for overloading a binary
operator, the only difference being that a friend function requires two arguments to be
explicitly passed to it, while a member function requires only one
...
csitnepal
...
meter + d2
...
centimeter + d2
...
getDist();
d3 = d1 + d2;
d3
...
feet && inch == e
...
csitnepal
...
4);
equal e2(6,4
...
h>
#include
...
h>
#define SZ 20
class string
{
private:
char str[SZ];
public:
string()
{
strcpy(str," ");
}
string(char s[])
{
strcpy(str,s);
}
void getstring()
{
cout<<"\nEnter a string ";
cin>>str;
}
int operator ==(string ss)
{
return(strcmp(str,ss
...
csitnepal
...
getstring();
if(s3 == s1)
cout<<"\nYou typed Nepal";
else if(s3 == s2)
cout<<"\nYou typed Kathmandu";
else
cout<<"\nNot of both";
getch();
return 0;
}
//Overloading + operator to concatenate two strings
#include
...
h>
#include
...
str) < SZ)
{
strcpy(temp
...
str,ss
...
csitnepal
...
display();
s2
...
display();
cout< getch();
return 0;
}
//Overloading < operator
class line
{
int feet;
float inch;
public:
line()
{}
line(int f,float i)
{
feet = f;
inch = i;
}
void display()
{
cout< }
int operator<(line);
};
int line::operator<(line l)
{
float l1 = feet + inch/12;
float l2 = l
...
inch/12;
if(l1 return 1;
else
return 0;
}
main()
{
ep
a
itn
Page 185
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
line l1(2,5
...
3);
if(l1 l1
...
display();
getch();
return 0;
}
Multiple Overloading
We have seen several different uses of + operator: - to add distance and to concatenate
strings
...
It selects the correct function to carry out the addition
based on the type of operand
...
ep
a
itn
Page 186
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
h>
#include
...
meter;
int cm = centimeter + d2
...
str) < SZ)
{
strcpy(temp
...
str,ss
...
csitnepal
...
getDist();
d3 = d1 + d2;
d3
...
display();
s2
...
display();
getch();
return 0;
}
General rules for overloading operators
There are some restrictions and limitations to be kept in mind while overloading
operators
...
New operators can not be created
...
It is not recommended to change the basic meaning of an operator
...
Overloaded operators follow syntax rules of the original operators
...
Friend functions can not be used to overload certain operators like =, ( ), [ ] and >
...
But those overloaded by a friend
functions take one reference argument
...
Binary operators such as +, -, *, and / must explicitly return a value
...
itn
Page 188
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Operator Overloading Restriction
Operator functions can not have default arguments
...
*, ?:, sizeof
...
Type Conversion (Data Conversion)
We use the assignment operator (=) to assign value of one variable to another
...
We have also noticed that = assigns the value of one
user defined object to another, provided that they are of the same type
...
The compiler
does not need any special instructions to use = for the assignment of user-defined objects
such as distance objects
...
But if the variables on different sides of the = are of different types, then the type of
variable on the right side of = needs to be converted to the type of left side variable
before the assignment takes place
...
Conversion Between Basic Types
Consider the statement,
intvar = floatvar;
where intvar is of type int and floatvar is of type float
...
There are many such
conversions: from float to double, char to float and so on
...
Such conversions are implicit conversion
...
For example,
ep
a
itn
Page 189
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
int total = 400;
float avg;
avg = float(total) / 5; // converts value of total to float before division takes place
...
Instead, we must write these routines
ourselves
...
These are sometimes
called conversion constructors
...
display();
getch();
}
From User-Defined to Basic Type
When class type data is converted into basic type data, it is called class to basic type
conversion
...
This type of
conversion takes place in casting operator
...
The syntax of casting operator function is
ep
a
itn
Page 190
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
operator typename()
{
………
...
}
This function converts a class type data to typename
...
The operator int() converts a class type object to
type int and so on
...
It must not specify a return type
...
class Stock
{
int items;
float price;
public:
Stock(int a,float p)
{
items = a;
price = p;
}
void putdata()
{
cout<<"Items: "< cout<<"Price: "< }
operator float()
{
return (items*price);
}
};
main()
{
Stock s(45,2
...
putdata();
cout<<"Total float value = "< getch();
return 0;
itn
Page 191
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
}
Another example
class DistConv
{
private:
int kilometers;
double meters;
static double kilometersPerMile;
public:
// This function converts a built-in type (i
...
miles) to the
// user-defined type (i
...
DistConv)
DistConv(double mile) // Constructor with one argument
{
double km = kilometersPerMile * mile ; // converts miles to
//kilometers
kilometers = int(km);
// converts float km to
//int and assigns to kilometer
meters = (km - kilometers) * 1000 ; // converts to meters
}
DistConv(int k, float m) // constructor with two arguments
{
kilometers = k ;
meters = m ;
}
// ********Conversion Function************
operator double()
// converts user-defined type i
...
// DistConv to a basic-type
{
// (double) i
...
meters
double K = meters/1000 ;
// Converts the meters to
// kilometers
K += double(kilometers) ;
// Adds the kilometers
return K / kilometersPerMile ; // Converts to miles
}
void display(void)
{
cout << kilometers << " kilometers and " << meters << " meters" ;
}
}; // End of the Class Definition
double DistConv::kilometersPerMile = 1
...
csitnepal
...
0 ;
// Uses the constructor with one argument
DistConv d2( 2, 25
...
255 kilometers = " << ml << " miles\n" ;
ml = d1 ;
// This form also uses conversion function
// and converts DistConv to miles
d1
...
255 kilometers = 1
...
72 meters = 5 miles*/
From One Class to Another Class Type
When a data of one class type is converted into data of another class type, it is called
conversion of one class to another class type
...
The class Y type data is
converted to the class X type data and converted value is assigned to the objx
...
This type of conversion is carried out by either constructor or
a conversion function
...
We know that the casting operator function
operator typename()
itn
Page 193
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Now consider a single-argument constructor function which serves as an instruction for
converting the argument’s type to the class type of which it is a member
...
The typename may be a
built-in type or user-defined type one
...
Therefore, when a class needs to be converted, a
casting operator function can be used (i
...
source class)
...
conversion
...
class Kilometers
{
private:
double kilometers;
public:
Kilometers(double kms)
{
kilometers = kms;
}
void display()
{
cout << kilometers << " kilometeres";
}
double getValue()
{
return kilometers;
}
};
itn
Page 194
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
class Miles
{
private:
double miles;
public:
Miles(double mls)
{
miles = mls;
}
void display()
{
cout << miles << " miles";
}
operator Kilometers()
{
return Kilometers(miles*1
...
getValue()/1
...
display();
cout << " = ";
k1
...
display();
cout << " = ";
m2
...
934 kilometeres
100 kilometeres = 62
...
csitnepal
...
csitnepal
...
getcode();
value = p
...
getprice();
}
};
main()
{
clrscr();
invent1 s1(100,5,140
...
putdata();
cout<<"Stock value"<<"\n";
cout<<"value = "< cout<<"Product details-invent2 type"<<"\n";
d1
...
csitnepal
...
Write a program to overload += operator
...
Write a program to overload = operator (It is already overloaded in C++)
...
10
...
11
...
Overload + operator to add two objects of class Length
...
Also facilitate the operations like L4 = L1 + 5 and L5 = 5 + L4 where L1,
L2, L3, L4 and L5 are objects of class Length
...
12
...
Assume that the class distance contains two data members (feet
(integer type) and inch (floating point type)
...
33 feet and 1 feet
= 12 inches)
13
...
e
...
Let P1
and P2 be the objects of this class where P1 is initialized to (20, 30)
...
itn
Page 198
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
14
...
Virtual Function and Run Time Polymorphism
Pointers
Pointers have a reputation for being hard to understand
...
Addresses are numbers, just as they
are for houses on a street
...
If you have 1MB of
memory, the highest address is 1,048,575; for 16 MB of memory, it is 16,777,215
...
New and Delete Operator
Pointer provides the necessary support for C++ powerful dynamic memory allocation
system
...
For eg- int arr[100];
reserves memory for 100 integers
...
We must know at the time we write the program how big the
array will be and it is not always possible to predict what the size of the array will be
...
This capability is provided by the new operator
...
The syntax for the
new operator is
= new ;
where = pointer variable
= char, int, float and so on
type of variable mentioned on the left hand side and the type mentioned on the right hand
side should match
...
csitnepal
...
For egchar *cptr;
cptr = new char[10];
allocates 10 bytes of memory and assigns the starting address to cptr
...
To ensure safe and efficient use of
memory, the new operator is matched by a corresponding delete operator that returns
memory to the operating system
...
However, this address is no longer valid, the memory it
points to may be changed to something entirely different but we do not use pointers
memory that has been deleted
...
For egdelete[] cptr;
//Example program that makes use of new and delete operator
#include
...
h>
class test
{
int x;
public:
void input()
{
cin>>x;
}
void display()
{
cout< }
};
main()
{
test *t = new test;
t->input();
t->display();
delete t;
getch();
return 0;
}
ep
a
itn
Page 200
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Polymorphism
In the programming sphere, polymorphism is broadly divided into two parts- the first part
being static polymorphism- exhibited by overloaded functions and the second being
dynamic polymorphism exhibited by late binding
...
Static polymorphism involves binding of functions on the basis of
number, type, and sequence of their arguments
...
This form of association is called early binding
...
The resolution is on the basis of number, type, and sequence of
arguments declared for each form of the function
...
void add(int, int);
void add(float, float);
Now, if the function add() is invoked, the parameters passed to it will determine which
version of the function will be executed
...
Dynamic Polymorphism
Dynamic polymorphism refers to an entity changing its form depending on the
circumstances
...
The term late binding refers to the resolution of the function to their
associated methods at run time instead of compile time
...
The compiler is unable to bind a call to a method since resolution depends
on the context of the call
...
Virtual Functions
Virtual means existing in appearance but not in reality
...
A function is made virtual by placing the keyword virtual
before its normal declaration
...
ep
a
itn
Page 201
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
h>
class Base
{
public:
void show()
{
cout<<"Base\n";
}
};
class Derv1 : public Base
{
public:
void show()
{
cout<<"Derv1\n";
}
};
class Derv2 : public Base
{
public:
void show()
{
cout<<"Derv2\n";
}
};
int main()
{
Derv1 d1;
Derv2 d2;
Base *ptr; // pointer to base class
ptr = &d1;
ptr->show();
ptr = &d2;
ptr->show();
getch();
return 0;
}
itn
Page 202
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Virtual Member Functions Accessed with Pointers
Let’s make a single change in the above program
...
#include
...
h>
l
Output of the program
Base
Base
The function in the base class is always executed
...
class Base
{
public:
virtual void show()
{
cout<<"Base\n";
}
};
class Derv1 : public Base
{
public:
void show()
{
cout<<"Derv1\n";
}
};
class Derv2 : public Base
{
public:
void show()
{
cout<<"Derv2\n";
}
};
int main()
{
Derv1 d1;
Derv2 d2;
Base *ptr;
ptr = &d1;
ptr->show();
ptr = &d2;
ptr->show();
getch();
return 0;
}
Output of the program
Derv1
Derv2
Now, as you can see, the member functions of the derived classes, not the base class, are
executed
...
So the same function call,
ep
a
itn
Page 203
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
ptr->show();
executes different functions, depending on the contents of ptr
...
Here,
the compiler does not know what class the contents of ptr may contain
...
Which version of show()
does the compiler call? In fact the compiler does not know what to do, so it arranges for
the decision to be deferred until the program is running
...
Abstract Classes and Pure Virtual Functions
An abstract class is one that is not used to create objects
...
A class is made an
abstract by placing at least one pure virtual function in the class
...
i
...
a pure virtual function can be
declared by equating it to zero
...
The =0 syntax is simply how we will tell the compiler that a function will be
pure
...
If a class does not
override the pure virtual function, then it becomes an abstract class itself, and we can not
instantiate objects from it
...
We can not create objects of the abstract class
...
This allows an abstract class to be used as a base class, pointers to which
can be used to select the proper virtual function
...
csitnepal
...
h>
#include
...
csitnepal
...
h>
#include
...
csitnepal
...
5) ? 1 : 0;
}
};
class professor : public person
{
private:
int numpubs;
public:
void getData()
{
person :: getName();
cout<<"\nEnter number of publications";
cin>>numpubs;
}
int isOutstanding()
{
return (numpubs > 100)?1 : 0;
}
};
main()
{
person *persptr[100];
int n = 0;
char choice;
do
{
cout<<"\nEnter student or professor(s/p)";
cin>>choice;
if(choice == 's')
persptr[n] = new student;
else
persptr[n] = new professor;
persptr[n++]->getData();
cout<<"\nAnother record? ";
cin>>choice;
}while(choice == 'y');
for(int j = 0;j < n; j++)
{
persptr[j]->putName();
if(persptr[j]->isOutstanding())
cout<<"\nThis person is outstanding";
}
getch();
return 0;
}
Friend class
The member functions of a class can all be made friends at the same time when we make
the entire class a friend
...
#include
...
h>
class alpha
{
int data;
public:
alpha()
{
data = 10;
}
friend class beta; // beta is friend class
};
class beta
{
public:
void func1(alpha a)
{
cout<
...
data;
}
};
main()
{
ep
a
itn
Page 207
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
alpha a;
beta b;
b
...
func2(a);
getch();
return 0;
}
In class alpha the entire class beta is defined as a friend
...
The this Pointer
The member functions of every object have access to a sort of magic pointer named this,
which points to the object itself
...
h>
#include
...
TestThisPointer();
m2
...
The this pointer can be treated like any
other pointer to an object, and can thus be used to access the data in the object it points
to
...
csitnepal
...
test();
getch();
return 0;
}
This program simply prints the value 10
...
csitnepal
...
class alpha
{
int data;
public:
alpha()
{}
alpha(int x)
{
data = x;
}
void display()
{
cout<}
alpha& operator = (alpha &a)
{
data = a
...
display();
l
This is exactly the same as referring to x directly
...
display();
getch();
return 0;
}
ep
a
itn
Page 210
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//using this pointer for returning value from member function
class Distance
{
int meter;
int centimeter;
public:
Distance()
{
meter = 0;
centimeter = 0;
}
Distance (int m, int cm)
{
meter = m;
centimeter = cm;
}
void getDist()
{
cout<<"Enter meter";
cin>>meter;
cout<<"Enter centimeter";
cin>>centimeter;
}
void show()
{
cout< }
Distance compare(Distance);
};
Distance Distance :: compare(Distance d2)
{
float dist1 = meter + (float)centimeter/100;
float dist2 = d2
...
centimeter/100;
if(dist1 < dist2)
return *this;
else
return d2;
}
main()
{
Distance d1(4,50);
Distance d2,d3,d4;
d2
...
compare(d2);
cout<<"Small lenght is: ";
d4
...
csitnepal
...
It supports the generic data types
and generic programming
...
Templates are a feature of the C++ programming language that allows functions and
classes to operate with generic types
...
A template is a way to specify generic code, with a placeholder for the type
...
Templates offer several advantages:
Templates are easier to write
...
Templates can be easier to understand, since they can provide a straightforward
way of abstracting type information
...
Because the types that templates act upon are known at
compile time, the compiler can perform type checking before errors occur
...
However, there are many differences between a macro like this:
#define min(i, j) (((i) < (j)) ? (i) : (j))
and a template:
template T min (T i, T j) { return ((i < j) ? i : j) }
Here are some problems with the macro:
Source: www
...
com (By:Tej Bahadur Shahi)
Page 212
l
ep
a
itn
There is no way for the compiler to verify that the macro parameters are of
compatible types
...
The i and j parameters are evaluated twice
...
Because macros are expanded by the preprocessor, compiler error messages will
refer to the expanded macro, rather than the macro definition itself
...
cs
Templates in c++ comes in two variations
a) function templates
b) class templates
Class template
The relationship between a class template and an individual class is like the relationship
between a class and an individual object
...
The general form of a class template is
Template
Class class_name
{
//class member with type T whenever appropriate
};
Example
#include
...
x = v1
...
y = v1
...
csitnepal
...
9,6
...
0,-2
...
Compiler generates classes for only the used types
...
Templates reduce the effort on coding for different data types to a single set of
code
...
Function template
To perform identical operations for each type of data compactly and conveniently, we use
function templates
...
Based on the
argument types provided in calls to the function, the compiler automatically instantiates
separate object code functions to handle each type of call appropriately
...
When the
compiler sees an instantiation of the function template, for example: the call max(10, 15)
in function main, the compiler generates a function max(int, int)
...
Page 214
itn
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
//function template
cs
template
l
#include
using namespace std ;
//max returns the maximum of the two elements
T max(T a, T b)
{
return a > b ? a : b ;
}
int main()
{
cout << "max(10, 15) = " << max(10, 15) << endl ;
cout << "max('k', 's') = " << max('k', 's') << endl ;
cout << "max(10
...
2) = " << max(10
...
2) << endl ;
return 0;
}
Output:
max(10, 15) = 15
max('k', 's') = s
max(10
...
2) = 15
...
The keyword class, within the angle brackets, might just as well be called type
...
The variable following the keyword class (T in
this example) is called the template argument
...
csitnepal
Title: C++
Description: A simple and easy note is here for u...I can bet u gonna pass any exam with this note...so guys what are you looking for??Download it and enjoy
NOTE: A function can, not only, take objects as arguments, but they can also
return object
...
In the above program if we modify the function sum() as follows:
Height Height::sum(Height h1,Height h2) //function with return type
Height
{
Height h3;
h3
...
inches + h2
...
feet= h3
...
inches= h3
...
feet = h3
...
feet + h2
...
Friend Function
A function is said to be a friend function of a class if it can access the members
(including private members) of the class even if it is not the member function of this
class
...
ep
a
itn
Page 32
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Characteristics of a friend function:
- A friend function can be either global or a member of some other class
...
- It cannot be called by using the object of the class since it is not in the scope
of the class
...
- Unlike member functions, it cannot access member names directly
...
x)
- It, generally, takes objects as arguments
...
Its definition is written somewhere
outside the class
...
class Avg
{
int n1,n2;
public:
void getn()
{
cin>>n1>>n2;
}
friend int average(Avg a);
};
//here “friend” is a keyword to specify that the function declared is a friend
function
//int is a return type of the friend function
//average is the name of the friend function
//Avg is the type of the argument type
//a is an argument
itn
Page 33
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
int main()
{
Avg obj;
obj
...
Perhaps the
function will take objects of the two classes as arguments, and operate on their private
l
int average(Avg a) //friend function definition
{
return((a
...
n2)/2);
}
data
...
Here is an example that
shows how friend functions can act as a bridge between two classes
...
h>
#include
csitnepal
...
data+b
...
get_data();
bb
...
In
some cases, it may be necessary that all objects of a class have access to the same copy of
a single variable
...
- Only one copy of the static member is created for the entire class and is shared
by all the objects of that class, no matter how many objects are created
...
- It is initialized to zero when the first object of its class is created
...
A static variable is declared using the “static” keyword
...
It is necessary since static data member are stored
void put_count()
separately, rather than as a part of the object
...
}
Eg
...
put_count();
b
...
put_count();
return(0);
ep
a
itn
Page 35
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
}
Output:
123
Static Member Function
In a class, functions can also be declared as static
...
class_name::function_name
ep
a
itn
Page 36
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Example
class A
{
int no;
static int count;
//static member
public:
void set_no()
{
count++;
no = count;
}
void put_no()
{
cout<<”No
...
set_no();
a2
...
set_no();
a2
...
put_no();
a2
...
Constructors and Destructors
We have seen, so far, a few examples of classes being implemented
...
For example, the statement
t
...
Similarly, the statement
t
...
All these function call statements are used
with the appropriate objects that have already been created
...
One of the aims of C++ is to create user-defined data types such as class that behave very
similar to the built-in types
...
For example,
int x = 10;
float y = 56
...
Similarly, when a variable of built-in type goes out of scope, the compiler automatically
destroys the variable
...
There are some features of class that enable us to initialize the objects when they are
created and destroy them when their presence is no longer necessary
...
csitnepal
...
This is known as automatic initialization of objects
...
Constructors
A constructor is a special member function whose task is to initialize the objects of its
class
...
The constructor is invoked whenever an
object of its associated class is created
...
-
They are also used to allocate memory for a class object
...
Constructor’s name is same as that of class name
...
They do not have return types, not even void and therefore, and they cannot return
any values
...
Constructor is NOT called when a pointer of a class is created
...
- Default constructors
- Parameterized Constructors
- Copy Constructors
Default Constructors
A constructor that does not take any parameter is called default constructor
...
1
...
And it does not do anything other than
allocating memory for the class object
...
If we provide a constructor without any arguments then that is the default
constructor
...
csitnepal
...
If we provide constructor with all default arguments, then that can also be
considered as the default constructor
...
Arguments are
passed when the objects are created
...
- by calling the constructor explicitly
- by calling the constructor implicitly
For eg
...
ep
a
itn
Page 39
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Copy Constructor
A copy constructor is called when an object is created by copying an existing object
...
A obj2(obj1);
The above statement would define the object obj2 and initialize it to the values of obj1
...
A copy constructor takes a reference to an object of the same class as itself (as an
argument)
...
When no copy
constructor is defined, the compiler supplies its own copy constructor
...
However, if obj1 and obj2 are objects, this
statement is legal and simply assigns the values of obj1 to obj2, member by member
...
Eg
...
info;
}
void display()
{
cout<
};
int main()
{
ep
a
itn
Page 40
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Data d1(5); //parameterized constructor is called
...
Data d3=d2; //again a copy constructor is called here
...
display();
cout<<”An info stored in d2”;
d2
...
display();
cout<<”An info stored in d4”;
d4
...
The first one d1 calls the parameterized
constructor, while the other two calls the copy constructor
The output will be
An info stored in d1 5
An info stored in d2 5
An info stored in d3 5
An info stored in d4 5
Constructor Overloading
The process of sharing the same name by two or more functions is referred to as function
overloading
...
In the above example of class Data, we have defined three constructors
...
The second gets invoked when we supply
one argument, while the third one gets invoked when an object is passed as an argument
...
Data obj1;
This statement would automatically invoke the first one
...
Eg
...
csitnepal
...
display();
obj2
...
display();
return(0);
}
Output:
000
5 10 15
6 10 20
In this program, there are two constructors
...
Such
a constructor is called a constructor with default argument
...
It is important to distinguish between the default constructor A::A() and the default
argument constructor A::A (int x = 0)
...
When called with no arguments, it becomes a
default constructor
...
ep
a
itn
Page 42
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Example
#include
h>
class test
{
int x,y;
public:
//test() // No need to use this default constructor
//{}
test(int p=10,int q = 20) // when this constructor is called with no arguments, it
{
// becomes default constructor
x = p;
y = q;
}
void display()
{
cout<<"X = "<
};
void main()
{
int x,y;
cin>>x>>y;
test t(x,y); // call to default argument constructor
t
...
display();
getch();
}
Dynamic initialization of objects
Class objects can be initialized dynamically (i
...
at the run time)
...
Advantage: various initialization formats can be provided using constructor overloading
...
l=1;
b=1;
area=1;
}
Area(int a, int br)
{
Area()
l
{
void main()
{
int l,b,area;
Area a1,a2;
public:
int l,b,len;
cin>>l>>b;
a1=Area(l,b);
cin>>len;
a2=Area(len);
--------- - -- - - - - - }
l=a;
b=br;
ep
a
class Area
{
cs
itn
Source: www
...
com (By:Tej Bahadur Shahi)
Page are
NOTE: In dynamic initialization, we 43 explicitly calling
the required constructor
...
area=l*b;
}
Area(int a)
{
l=a;
b=0;
area=l*l;
}
};
Destructors
Destructors are the special function that destroys the object that has been created by a
constructor
...
Destructors, too, have special name, a class name
preceded by a tilde sign (~)
...
A destructor for the class Area will look like
~Area()
{-----------}
Destructor gets invoked, automatically, when an object goes out of scope (i
...
exit from
the program, or block or function)
...
Destructor
never takes any argument, nor does it return any value
...
#include
h>
class A
{
static int count;
public:
A()
{
count++;
cout<
~A()
{
cout<
}
};
int A::count;
ep
a
itn
Page 44
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
main()
{
A a1,a2,a3;
getch();
return 0;
}
Operator Overloading
The concept of overloading can be applied to operators as well
...
It provides a flexible option for
the operations of new definitions for most of the C++ operators
...
In general,
a = b + c; works only with basic types like ‘int’ and ‘float’, and attempting to
apply it when a, b and c are objects of a user defined class will cause complaints from the
compiler
...
There are two types of operator overloading
Unary operator overloading and
Binary operator overloading
Unary operator overloading
Unary operators are those operators that act on a single operand
...
The following program overloads the ++ unary operator for the distance class
to increment the data number by one
...
csitnepal
...
display();
}
In the above example, the ++ unary operator has been overloaded in the function void
Distance :: operator ++(void)
...
This function is called at the second line ‘++dist’ in the main
...
list)
{
//func body
}
The keyword ‘operator’ is used to overload an operator
...
//Another Example - overloading unary minus operator
ep
a
itn
Page 46
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
class abc
{
int x,y,z;
public:
void getdata(int a,int b,int c)
{
x = a;
y = b;
z = c;
}
void display()
{
cout<
void operator -();
};
void abc::operator-()
{
x = -x;
y = -y;
z = -z;
}
main()
{
abc a;
a
...
display();
-a;
a
...
If we use a statement like this
c1 = ++c2;
For this we have to define the ++ operator to have a return type object of a class in the
operator++ function
...
the example given
below illustrates this
...
csitnepal
...
put_count();
c2
...
put_count();
c2
...
What about postfix, where the
variable is incremented after its value is used in the expression?
c1++
to make both versions of the increment operator work, we define two overloaded ++
operators as follows
class Counter
{
int count;
public:
Counter()
{
count = 0;
}
Counter(int c)
{
count = c;
}
ep
a
itn
Page 48
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Counter operator++()
{
return Counter(++count);
}
Counter operator++(int)
{
return Counter(count++);
}
void put_count()
{
cout<
};
main()
{
Counter c1,c2,c3;
c1
...
put_count();
c2 = ++c1;
c3 = c2++;
c1
...
put_count();
c3
...
The one, for
prefix notation, is
Counter operator ++()
The one, for postfix notation, is
Counter operator ++(int)
The only difference is the int in the parentheses
...
It’s simply a signal to the compiler to create the postfix version of
the operator
...
Overloading binary operators
Binary operators are those that work on two operands
...
Overloading a binary operator is similar to overloading unary operator except that a
binary operator requires an additional parameter
...
It adds two objects of type ‘distance’
...
csitnepal
...
csitnepal
...
The argument on the left side the operator (d1 here) is the
l
};
Distance Distance :: operator + (Distance d2)
{
int m = meter + d2
...
centimeter;
if(cm >= 100)
{
cm -= 100;
m++;
}
return Distance (m,cm);
}
main()
{
Distance d1(4,50);
Distance d2,d3,d4;
d2
...
operator+(d1); // usual function call syntax
d3
...
show();
return 0;
}
object of which the operator is a member
...
Overloading Binary Operators Using Friend Function
Friend functions may be used in the place of member functions for overloading a binary
operator, the only difference being that a friend function requires two arguments to be
explicitly passed to it, while a member function requires only one
...
csitnepal
...
meter + d2
...
centimeter + d2
...
getDist();
d3 = d1 + d2;
d3
...
feet && inch == e
...
csitnepal
...
4);
equal e2(6,4
...
h>
#include
h>
#define SZ 20
class string
{
private:
char str[SZ];
public:
string()
{
strcpy(str," ");
}
string(char s[])
{
strcpy(str,s);
}
void getstring()
{
cout<<"\nEnter a string ";
cin>>str;
}
int operator ==(string ss)
{
return(strcmp(str,ss
...
csitnepal
...
getstring();
if(s3 == s1)
cout<<"\nYou typed Nepal";
else if(s3 == s2)
cout<<"\nYou typed Kathmandu";
else
cout<<"\nNot of both";
getch();
return 0;
}
ep
a
itn
Page 54
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//Overloading + operator to concatenate two strings
#include
h>
#include
str) < SZ)
{
strcpy(temp
...
str,ss
...
display();
s2
...
display();
cout<
return 0;
}
ep
a
itn
Page 55
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//Overloading < operator
class line
{
int feet;
float inch;
public:
line()
{}
line(int f,float i)
{
feet = f;
inch = i;
}
void display()
{
cout<
int operator<(line);
};
int line::operator<(line l)
{
float l1 = feet + inch/12;
float l2 = l
...
inch/12;
if(l1
else
return 0;
}
main()
{
line l1(2,5
...
3);
if(l1
...
display();
getch();
return 0;
}
Multiple Overloading
We have seen several different uses of + operator: - to add distance and to concatenate
strings
...
It selects the correct function to carry out the addition
based on the type of operand
...
ep
a
itn
Page 56
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
h>
#include
csitnepal
...
meter;
int cm = centimeter + d2
...
str) < SZ)
{
strcpy(temp
...
str,ss
...
getDist();
d3 = d1 + d2;
d3
...
display();
s2
...
display();
getch();
return 0;
}
General rules for overloading operators
There are some restrictions and limitations to be kept in mind while overloading
operators
...
New operators can not be created
...
It is not recommended to change the basic meaning of an operator
...
Overloaded operators follow syntax rules of the original operators
...
Friend functions can not be used to overload certain operators like =, ( ), [ ] and >
...
But those overloaded by a friend
functions take one reference argument
...
Binary operators such as +, -, *, and / must explicitly return a value
...
ep
a
itn
Page 58
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Operator Overloading Restriction
Operator functions can not have default arguments
...
*, ?:, sizeof
...
Type Conversion (Data Conversion)
We use the assignment operator (=) to assign value of one variable to another
...
We have also noticed that = assigns the value of one
user defined object to another, provided that they are of the same type
...
The compiler
does not need any special instructions to use = for the assignment of user-defined objects
such as distance objects
...
But if the variables on different sides of the = are of different types, then the type of
variable on the right side of = needs to be converted to the type of left side variable
before the assignment takes place
...
Conversion Between Basic Types
Consider the statement,
itn
Page 59
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
where intvar is of type int and floatvar is of type float
...
There are many such
l
intvar = floatvar;
conversions: from float to double, char to float and so on
...
Such conversions are implicit conversion
...
For example,
int total = 400;
float avg;
avg = float(total) / 5; // converts value of total to float before division takes place
...
Instead, we must write these routines
ourselves
...
These are sometimes
called conversion constructors
...
display();
getch();
ep
a
itn
Page 60
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
}
From User-Defined to Basic Type
When class type data is converted into basic type data, it is called class to basic type
conversion
...
This type of
conversion takes place in casting operator
...
The syntax of casting operator function is
operator typename()
{
………
...
}
This function converts a class type data to typename
...
The operator int() converts a class type object to
type int and so on
...
It must not specify a return type
...
class Stock
{
int items;
float price;
public:
Stock(int a,float p)
{
items = a;
price = p;
}
void putdata()
{
cout<<"Items: "<
operator float()
{
return (items*price);
}
Stock s(45,2
...
csitnepal
...
putdata();
cout<<"Total float value = "<
return 0;
}
Another example
class DistConv
{
private:
int kilometers;
double meters;
static double kilometersPerMile;
public:
// This function converts a built-in type (i
...
miles) to the
// user-defined type (i
...
DistConv)
DistConv(double mile) // Constructor with one argument
{
double km = kilometersPerMile * mile ; // converts miles to
//kilometers
kilometers = int(km);
// converts float km to
//int and assigns to kilometer
meters = (km - kilometers) * 1000 ;
// converts to meters
ep
a
itn
Page 62
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
}
DistConv(int k, float m) // constructor with two arguments
{
kilometers = k ;
meters = m ;
}
// ********Conversion Function************
operator double()
// converts user-defined type i
...
// DistConv to a basic-type
{
// (double) i
...
meters
double K = meters/1000 ;
// Converts the meters to
// kilometers
K += double(kilometers) ;
// Adds the kilometers
return K / kilometersPerMile ; // Converts to miles
}
void display(void)
{
cout << kilometers << " kilometers and " << meters << " meters" ;
}
}; // End of the Class Definition
double DistConv::kilometersPerMile = 1
...
0 ;
// Uses the constructor with one argument
DistConv d2( 2, 25
...
255 kilometers = " << ml << " miles\n" ;
ml = d1 ;
// This form also uses conversion function
// and converts DistConv to miles
d1
...
255 kilometers = 1
...
72 meters = 5 miles*/
From One Class to Another Class Type
When a data of one class type is converted into data of another class type, it is called
conversion of one class to another class type
...
csitnepal
...
The class Y type data is
converted to the class X type data and converted value is assigned to the objx
...
This type of conversion is carried out by either constructor or
a conversion function
...
We know that the casting operator function
Converts the class object of which it is a member to typename
...
In the case of conversion between objects,
typename refers to the destination class
...
e
...
The conversion takes place in the
source class and the result is given to the destination class object
...
This implies
that the argument belongs to the source class and is passed to the destination class for
conversion
...
class Kilometers
{
private:
double kilometers;
public:
Kilometers(double kms)
{
kilometers = kms;
}
void display()
{
cout << kilometers << " kilometeres";
}
double getValue()
{
return kilometers;
}
};
ep
a
itn
Page 64
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
class Miles
{
private:
double miles;
public:
Miles(double mls)
{
miles = mls;
}
void display()
{
cout << miles << " miles";
}
operator Kilometers()
{
return Kilometers(miles*1
...
getValue()/1
...
display();
cout << " = ";
k1
...
display();
cout << " = ";
m2
...
934 kilometeres
100 kilometeres = 62
...
csitnepal
...
csitnepal
...
getcode();
value = p
...
getprice();
}
};
main()
{
clrscr();
invent1 s1(100,5,140
...
putdata();
cout<<"Stock value"<<"\n";
cout<<"value = "<
d1
...
csitnepal
...
Write a program to overload += operator
...
Write a program to overload = operator (It is already overloaded in C++)
...
3
...
4
...
Overload + operator to add two objects of class Length
...
Also facilitate the operations like L4 = L1 + 5 and L5 = 5 + L4 where L1,
L2, L3, L4 and L5 are objects of class Length
...
5
...
Assume that the class distance contains two data members (feet
(integer type) and inch (floating point type)
...
33 feet and 1 feet
= 12 inches)
6
...
e
...
Let P1
and P2 be the objects of this class where P1 is initialized to (20, 30)
...
itn
Page 68
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
7
...
Inheritance
Inheritance is the most powerful feature of object-oriented programming
...
The class inherits all the capabilities of the base class but can add refinements of
its own
...
Inheritance is also called a ‘kind of relationship’
...
Once a class has been written and tested, its features can be adapted by
other programmers whenever required
...
csitnepal
...
Inheritance
Types
There are 5 types of inheritance
1) Single Inheritance – when a class is derived from only one base class, then it is called
single inheritance
...
csitnepal
...
// body part
…
}
public:
{
…
...
}
};
class B : public A // derived class B
{
……
…
...
It can be represented as,
Base class A
Base class B
Derived class C
Egclass A
{
……
...
csitnepal
...
……
};
class C : public A, public B
{
……
...
3) Hierarchical Inheritance: When two or more than two classes are derived from one
base class, it is called hierarchical inheritance
...
………
...
……
};
class C : public A
{
………
………
};
Here two classes B and C are derived from same base class A
...
csitnepal
...
g
...
…
...
……
};
class C : public B
{
…
...
};
In this example class B is derived from base class A and class C is derived from derived
class B
...
csitnepal
...
gclass student
{
……
…
...
……
...
};
class result : public test, public sport
{
……
…
...
The class test and sport are derived from
student and class result is derived from both test and sport classes
...
itn
Page 74
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Sub-class Definition
A subclass can be defined by specifying its relationship with base class along with its
own details
...
………
};
baseclass-name
The colon indicates that the inheritance has been used
...
e
...
The visibility mode specifies whether the features of the base class are
derived privately, publicly or protectedly
...
The three visibility modes are
public
private
protected
When the base class is publicly inherited, all the public members of the base class
become public members of the derived class
...
All the protected members become protected members of the
derived class
...
So, these can not be accessed
outside the class directly through the derived class object, but might be accessed through
public functions in the derived class
...
NOTE: private members can not be inherited at all
...
When a member is defined with protected access specifier, these members can be
accessed from that class and also from the derived class of this base class
...
i
...
protected members act as public for
derived class and private for other classes
...
csitnepal
...
Consider the program
#include
This means, like a
private inheritance, these members can not be directly accessed through object of the
derived class
...
Whereas, unlike a private
inheritance, they can still be inherited and accessed by subsequent derived classes
...
class aclass
{
public:
void disp(void)
{
cout<<”Base”<
};
class bclass : public aclass
{
public:
void disp(void)
{
cout<<”Derived”<
};
void main()
{
bclass Bvar;
Bvar
...
If the function is invoked from an object of the derived class, then the function in
the derived is executed
...
Ambiguities in Multiple Inheritance
When a class inherits from multiple base classes, a whole part of ambiguities creep in
...
csitnepal
...
h>
class base1
{
public:
void disp(void)
{
cout<<”Base1”<
};
class base2
{
public:
void disp(void)
{
cout<<”Base2”<
itn
Page 77
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Here, the reference to disp() is ambiguous because the compiler does not know whether
disp() refers to the member in class base1 or base2
...
base1::disp();
Dvar
...
That is, the members can be
redefined in the derived class
...
};
class derived : public base1, public base2
{
public:
void disp(void)
{
base1::disp();
base2::disp();
cout<<”Derived class”<
};
void main()
{
derived Dvar;
Dvar
...
disp(); // Ambiguous
}
}
Another ambiguity that arises in multiple inheritance is the possibility of the derived class
having multiple copies of the same base class
...
B and C in
turn are derived from class A
...
There are two ways of resolving this ambiguity
...
Containership
When a class contains object of another class as its member data, it is termed as
containership
...
Containership
is also termed as “class within class”
...
A obj1;
…
...
So
B is the container class
...
csitnepal
...
Containership is useful with classes that act like a data type
...
l
‘containership’ is also called ‘has-a’ relationship
...
This is
because B has all the characteristics of A, and in addition some of its own
...
itn
Page 79
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
class Manager
{
char name[20];
int age;
public:
void getdata()
{
cin>>name>>age;
}
void putdata()
{
cout<
};
class Employee // Employee is container class
{
char department[20];
Manager m; // Object of class Manager
public:
void getdata()
{
m
...
putdata();
cout<
};
void main()
{
Employee e;
e
...
putdata();
getch();
}
Abstract Class
An abstract class is one that is not used to create objects
...
It is a design concept in program development and provides a
base upon which other classes may be built
...
When the same class is
inherited more than once via multiple paths, multiple copies of the base class members
are created in memory
...
A base class inheritance can be specified as a virtual using
the virtual qualifier
...
…
...
…
...
};
class C : public B1, public B2
{
……
……
};
Keywords ‘virtual’ and ‘public’ can be used in either way
...
csitnepal
...
However, if any base
class contains a constructor with one or more arguments, then it is mandatory for the
derived class to have a constructor and pass the arguments to the base class constructors
...
Thus, it
makes sense for the derived class to pass arguments to the base class constructor
...
Since there is only one copy, there is no ambiguity
...
Since the derived class takes the responsibility of supplying initial values to its base
classes, we supply the initial values that are required by all the classes together, when a
derived class object is declared
...
The constructor of the derived class receives the entire list of values as its arguments and
passes them onto the base constructors in the order in which they are declared in the
derived class
...
Example-
ep
a
itn
Page 81
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
5,50,60);
g
...
show_y();
g
...
Since the derived class contains more than one
Constructors and/or Destructors, it becomes confusing which one will be called when
...
This article will clear all this!
Consider the following example program:
// -- INHERITANCE -// Constructors, Destructors
// and Inheritance
#include
csitnepal
...
One more example will clear the confusions, if any
...
h>
ep
a
itn
Page 83
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
// base class (1)
class base
{
public:
base(){cout<<"Constructing Base\n";}
~base(){cout<<"Destructing Base\n";}
};
// derived class
// derived form 'base'
class derived1:public base
{
public:
derived1(){cout<<"Constructing Derived1\n";}
~derived1(){cout<<"Destructing Derived1\n";}
};
// derived from a derived class
// 'derived1'
class derived2:public derived1
{
public:
derived2(){cout<<"Constructing Derived2\n";}
~derived2(){cout<<"Destructing Derived2\n";}
};
void main(void)
{
derived2 obj;
// do nothing else, only
// construct and destruct
// the inherited class object
}
OUTPUT:
Constructing Base
Constructing Derived1
Constructing Derived2
Destructing Derived2
Destructing Derived1
Destructing Base
itn
Page 84
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Lab Sheet - 3
Employee
Name
ID
getdata()
putdata()
Manager
ComputerOperator
Department
Typing_Speed
getdata()
putdata()
getdata()
putdata()
1
...
Also write a
main() function to test the classes, Manager and ComputerOperator, by creating
their objects, taking input and displaying the corresponding values
...
Imagine a college hires some lecturers
...
Create a class called lecturer that stores the
ID, and the name of lecturers
...
Each of these three classes should have a readdata() function to get its
data from the user, and a printdata() function to display its data
...
3
...
Create a class Automobile that stores production
date and price
...
Each
of these classes should have member functions to get data and set data
...
itn
Page 85
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
4
...
From this class derive two classes: Bowler and Batsman
...
Use appropriate member functions
in all classes to read and display respective data
...
Define a base class Shape having data member radius (int)
...
Write methods to compute the area of
circle and sphere
...
Create classes Book having data members name of author (string), price (float)
and class Stock having data members number of books (int) and category (string)
...
All the classes should have functions having same name
...
Virtual Function and Run Time Polymorphism
Pointers
Pointers have a reputation for being hard to understand
...
Addresses are numbers, just as they
are for houses on a street
...
If you have 1MB of
memory, the highest address is 1,048,575; for 16 MB of memory, it is 16,777,215
...
New and Delete Operator
Pointer provides the necessary support for C++ powerful dynamic memory allocation
system
...
ep
a
itn
Page 86
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
For eg- int arr[100];
reserves memory for 100 integers
...
We must know at the time we write the program how big the
array will be and it is not always possible to predict what the size of the array will be
...
This capability is provided by the new operator
...
The syntax for the
new operator is
where
type of variable mentioned on the left hand side and the type mentioned on the right hand
side should match
...
For egchar *cptr;
cptr = new char[10];
allocates 10 bytes of memory and assigns the starting address to cptr
...
To ensure safe and efficient use of
memory, the new operator is matched by a corresponding delete operator that returns
memory to the operating system
...
However, this address is no longer valid, the memory it
points to may be changed to something entirely different but we do not use pointers
memory that has been deleted
...
For egdelete[] cptr;
ep
a
itn
Page 87
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//Example program that makes use of new and delete operator
#include
h>
class test
{
int x;
public:
void input()
{
cin>>x;
}
void display()
{
cout<
};
main()
{
test *t = new test;
t->input();
t->display();
delete t;
getch();
return 0;
}
Polymorphism
In the programming sphere, polymorphism is broadly divided into two parts- the first part
being static polymorphism- exhibited by overloaded functions and the second being
dynamic polymorphism exhibited by late binding
...
csitnepal
...
A function is said to exhibit dynamic polymorphism when it exists in
more than one form, and calls to its various forms are resolved dynamically when the
l
Static Polymorphism
Static polymorphism refers to an entity existing in different physical forms
simultaneously
...
The various types of parameters are
specified in the function declaration, and therefore the function can be bound to the calls
at compile time
...
The term early binding
stems from the fact that when the program is executed, the calls are already bound to the
appropriate functions
...
Consider the following function
declaration
...
This resolution is done at compile time
...
The term late binding refers to the resolution of the function to their
associated methods at run time instead of compile time
...
The compiler is unable to bind a call to a method since resolution depends
on the context of the call
...
Virtual Functions
Virtual means existing in appearance but not in reality
...
A function is made virtual by placing the keyword virtual
before its normal declaration
...
ep
a
itn
Page 89
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
h>
class Base
{
public:
void show()
{
cout<<"Base\n";
}
};
class Derv1 : public Base
{
public:
void show()
{
cout<<"Derv1\n";
}
};
class Derv2 : public Base
{
public:
void show()
{
cout<<"Derv2\n";
}
};
int main()
{
Derv1 d1;
Derv2 d2;
Base *ptr; // pointer to base class
ptr = &d1;
ptr->show();
ptr = &d2;
ptr->show();
getch();
return 0;
}
itn
Page 90
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Virtual Member Functions Accessed with Pointers
Let’s make a single change in the above program
...
#include
h>
class Base
{
public:
virtual void show()
{
cout<<"Base\n";
}
};
class Derv1 : public Base
{
public:
void show()
{
cout<<"Derv1\n";
}
};
class Derv2 : public Base
{
public:
void show()
{
cout<<"Derv2\n";
}
l
Output of the program
Base
Base
The function in the base class is always executed
...
};
int main()
{
Derv1 d1;
Derv2 d2;
Base *ptr;
ptr = &d1;
ptr->show();
ptr = &d2;
ptr->show();
getch();
return 0;
}
Output of the program
Derv1
Derv2
Now, as you can see, the member functions of the derived classes, not the base class, are
executed
...
So the same function call,
ptr->show();
executes different functions, depending on the contents of ptr
...
Here,
the compiler does not know what class the contents of ptr may contain
...
Which version of show()
does the compiler call? In fact the compiler does not know what to do, so it arranges for
the decision to be deferred until the program is running
...
Abstract Classes and Pure Virtual Functions
An abstract class is one that is not used to create objects
...
A class is made an
abstract by placing at least one pure virtual function in the class
...
i
...
a pure virtual function can be
declared by equating it to zero
...
csitnepal
...
The =0 syntax is simply how we will tell the compiler that a function will be
pure
...
If a class does not
override the pure virtual function, then it becomes an abstract class itself, and we can not
instantiate objects from it
...
We can not create objects of the abstract class
...
This allows an abstract class to be used as a base class, pointers to which
can be used to select the proper virtual function
...
csitnepal
...
h>
#include
csitnepal
...
h>
#include
5) ? 1 : 0;
}
};
class professor : public person
{
private:
int numpubs;
public:
void getData()
{
person :: getName();
cout<<"\nEnter number of publications";
cin>>numpubs;
}
int isOutstanding()
{
return (numpubs > 100)?1 : 0;
}
};
main()
{
person *persptr[100];
int n = 0;
char choice;
do
{
cout<<"\nEnter student or professor(s/p)";
cin>>choice;
if(choice == 's')
persptr[n] = new student;
else
persptr[n] = new professor;
persptr[n++]->getData();
cout<<"\nAnother record? ";
cin>>choice;
}while(choice == 'y');
for(int j = 0;j < n; j++)
{
persptr[j]->putName();
if(persptr[j]->isOutstanding())
cout<<"\nThis person is outstanding";
}
getch();
return 0;
}
Friend class
The member functions of a class can all be made friends at the same time when we make
the entire class a friend
...
ep
a
itn
Page 94
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
h>
class alpha
{
int data;
public:
alpha()
{
data = 10;
}
friend class beta; // beta is friend class
};
class beta
{
public:
void func1(alpha a)
{
cout< ...
data;
}
};
main()
{
alpha a;
beta b;
b
...
func2(a);
getch();
return 0;
}
In class alpha the entire class beta is defined as a friend
...
The this Pointer
The member functions of every object have access to a sort of magic pointer named this,
which points to the object itself
...
csitnepal
...
h>
#include
TestThisPointer();
m2
...
The this pointer can be treated like any
other pointer to an object, and can thus be used to access the data in the object it points
to
...
test();
getch();
return 0;
}
This program simply prints the value 10
...
csitnepal
...
class alpha
{
int data;
l
This is exactly the same as referring to x directly
...
data;
return *this;
}
};
main()
{
alpha a1(50);
alpha a2;
a2 = a1; // calls overloaded operator =
a1
...
display();
getch();
return 0;
}
ep
a
itn
Page 97
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//using this pointer for returning value from member function
class Distance
{
int meter;
int centimeter;
public:
Distance()
{
meter = 0;
centimeter = 0;
}
Distance (int m, int cm)
{
meter = m;
centimeter = cm;
}
void getDist()
{
cout<<"Enter meter";
cin>>meter;
cout<<"Enter centimeter";
cin>>centimeter;
}
void show()
{
cout<
Distance compare(Distance);
itn
Page 98
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
};
Distance Distance :: compare(Distance d2)
{
float dist1 = meter + (float)centimeter/100;
float dist2 = d2
...
centimeter/100;
if(dist1 < dist2)
return *this;
else
return d2;
}
main()
{
Distance d1(4,50);
Distance d2,d3,d4;
d2
...
compare(d2);
cout<<"Small lenght is: ";
d4
...
Programs can
be designed to perform the read and write operations on these files
...
Data transfer between the console unit and the program
...
Data transfer between the program and a disk file
...
It uses file streams as an interface between the programs and the
files
...
In other words, the input
stream extracts (or reads) data from the file and the output stream inserts (or writes) data
to the file
...
csitnepal
...
Similarly, the output operation involves establishing an output
stream with the necessary links with the program and the output file
...
These include ifstream, ofstream and fstream
...
These classes, designed to
manage the disk files, are declared in fstream and therefore we must include this file in
any program that uses files
...
stream classes for file I/O operations
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files
...
A file stream can be
defined using the classes ifstream, ofstream, and fstream
...
A
file can be opened in two ways
Opening Files Using Constructor
Opening a file using constructor involves the following steps:
itn
Page 100
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
1
...
Using the member function open() of the class
1
...
That is
to say, the class ofstream is used to create the output stream and the class
ifstream to create the input stream
...
Initialize the file object with the desired filename
...
h>
#include
h>
void main()
{
char name[20];
int age;
char sec;
ofstream ofile("Student
...
close();
ifstream ifile("student
...
close();
getch();
}
When a file is opened for writing only, a new file is created if there is no file of that
name
...
Opening Files Using open()
The function open() can be used to open multiple files that use the same stream object
...
This
is done as
file-stream-class
stream-object;
stream-object
...
csitnepal
...
h>
#include
h>
main()
{
char name[20];
int age,salary;
char sec;
ofstream ofile;
ofile
...
txt");
cout<<"\nEnter name, age section: ";
cin>>name>>age>>sec;
ofile<
...
open("teacher
...
close();
getch();
}
File Modes with open()
The open function can take two arguments, the second one for specifying the file mode
...
open(“filename”, mode);
The second argument (called file mode parameter) specifies the purpose for which the
file is opened
...
ep
a
itn
Page 102
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
put() and get() Functions
The function put() writes a single character to the associated stream
...
#include
h>
#include
open("myfile
...
get(ch);
while(ch != '\n')
{
file
...
get(ch);
}
file
...
open("myfile
...
get(ch);
cout<
file
...
This means that the values are stored in the disk file in the same format in
which they are stored in the internal memory
...
But a 4 digit int will take four
bytes to store it in the character form
...
The first is the address of the variable, and the second is the length of that variable in
bytes
...
ep
a
itn
Page 103
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//writing array of integers using write()
#include
h>
#include
open("myfile
...
write((char*)&x,sizeof(x));
file
...
open("myfile
...
read((char*)&x,sizeof(x));
for(i = 0;i < 4;i++)
cout<
}
Writing and Reading Class Objects (Object I/O)
When writing an object we generally want to use binary mode
...
The binary input output functions
write() and read() are used for this
...
h>
#include
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
{
cin>>name>>age;
}
void showData()
{
cout<
};
main()
{
ep
a
itn
Page 104
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
person p,q;
fstream file;
file
...
dat",ios::out|ios::binary);
cout<<"\nEnter person's data: ";
p
...
write((char *)(&p),sizeof(p));
file
...
open("person
...
read((char *)(&q),sizeof(q));
q
...
csitnepal
...
h>
#include
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
{
cin>>name>>age;
}
void showData()
{
cout<
};
main()
{
char ch;
person p;
fstream file;
file
...
dat",ios::out|ios::in|ios::binary);
do
{
cout<<"\nEnter person's data: ";
p
...
write((char *)(&p),sizeof(p));
cout<<"Enter another person? ";
cin>>ch;
}while(ch == 'y');
file
...
read((char *)(&p),sizeof(p));
while(!file
...
showData();
file
...
These are also called the current get position and the current put position, or
simply the current position
...
The seekg() and tellg() functions allow us to set and
examine the get pointer, and the seekp() and tellp() functions perform these same actions
on the put pointer
...
The argument
to these functions represents the absolute position in the file
...
The refposition takes one of the
following three constants defined in the class ios
ios :: beg
ios :: cur
ios :: end
start of file
current position of the pointer
end of the file
...
If file is an object of ofstream, then some some
sample pointer offset calls and their actions are:
Action
go to start
stay at the current position
go to the end of file
...
csitnepal
...
h>
ep
a
Seek call
file
...
seekg(0,ios::cur);
file
...
seekg(m,ios::beg);
file
...
csitnepal
...
h>
#include
open("group
...
seekg(0,ios::end);
int endposition = file
...
seekg(pos);
file
...
showData();
cout<<"\nRecords in file are:\n";
file
...
read((char*)&p,sizeof(p));
while(!file
...
showData();
file
...
close();
getch();
return 0;
}
// File copy program
...
#include
h>
#include
h>
void main()
{
char ch;
fstream file1,file2;
file1
...
txt",ios::out|ios::in);
file1<<"welcome to object oriented programming";
file1
...
open("test1
...
open("test2
...
get(ch);
ch = toupper(ch);
file2
...
close();
file2
...
open("test2
...
get(ch);
cout<
file2
...
Some functions are
good()
returns true if end of file is encountered while reading, otherwise return
returns true when an input or output operation has failed
...
returns true if no error has occurred
...
csitnepal
...
h>
#include
fail()
bad()
#include
open("myfile
...
fail())
{
cout<<"\nCould not open the file";
}
else
{
while(file)
{
file
...
close();
}
getch();
}
ep
a
itn
Page 109
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
h>
#include
open("myfile
...
good())
{
cout<<"\nCould not open the file";
}
else
{
while(file)
{
file
...
close();
}
getch();
}
Namespace
Namespaces allow to group entities like classes, objects and functions under a name
...
The
format
of
namespaces
is:
namespace
{
entities
}
identifier
Where identifier is any valid identifier and entities is the set of classes, objects and
functions that are included within the namespace
...
In order to access these variables from outside the
”myNamespace” namespace we have to use the scope operator ::
...
csitnepal
...
1416;
}
int main () {
cout << first::var << endl;
cout << second::var << endl;
return 0;
}
In this case, there are two global variables with the same name: var
...
No redefinition errors happen thanks to
namespaces
...
Example program2
#include
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
namespace second
{
double x = 3
...
7183;
}
itn
Page 111
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
int main () {
using namespace first
cout << x << endl;
cout << y << endl;
using namespace second
cout<
}
Templates
(Meaning to word: A document or file or entity having a preset format, used as a
starting point for a particular application so that the format does not have to be recreated
each time it is used)
A template is one of the recently added feature in c++
...
Generic programming is an approach where generic data types
are used as parameters in algorithms so that they can work for a variety of suitable data
types
...
This allows a function or class to work on many
different data types without being rewritten for each one
...
Note that the
type is the only "parameter" of a template, but a very powerful one, since anything from a
function to a class (or a routine) can be specified in "general" terms without concerning
yourself about the specific type
...
csitnepal
...
You create only one generic version of your class or
function instead of manually creating specializations
...
Templates are typesafe
...
Templates and Macros
In many ways, templates work like preprocessor macros, replacing the templated variable
with the given type
...
The macro is expanded without any special type checking
...
For example, if either parameter has a
post incremented variable, the increment is performed two times
...
Also, the
macro will show up in expanded form during debugging
...
An individual class defines how a group of
objects can be constructed, while a class template defines how a group of classes can be
generated
...
h>
ep
a
itn
Page 113
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
template
class vec {
T x;
T y;
public:
vec(T f1, T f2)
{
x=f1;
y=f2;
}
vec()
{ }
vec operator+(const vec& v1)
{
vec result;
result
...
x+this->x;
result
...
y+this->y;
return result;
}
};
int main() {
vec
vec
vec
vec
...
7);
vec
...
2);
vec
}
Advantages of C++ Class Templates:
Function template
itn
Page 114
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
One C++ Class Template can handle different types of parameters
...
If the template is instantiated
for int type, compiler generates only an int version for the c++ template class
...
Testing and debugging efforts are reduced
...
we can write a single function template definition
...
Syntax:
The general form of a function template is
Template
returnType function_name (argument of type T)
{
//body of function with type T whenever appropriate
}
Using Template Functions: example
Using function templates is very easy: just use them like regular functions
...
Similarly the compiler
generates definitions for max(char, char) and max(float, float) in this case
...
1, 15
...
1, 15
...
csitnepal
...
1, 15
...
2
itn
Page 116
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
The template keyword signals the compiler that I’m about to define a function template
...
As
you’ve seen, you can define your own data types using classes, so there’s really no
distinction between types and classes
...
Classes and Objects
One of the unique facilities provided by C language is “structure”
...
It was termed as a user defined data-type
...
Eg
...
- They don’t allow data hiding
...
- C does not allow the structure data type to be treated like built in data type
...
But C++ has expanded its
capabilities further to suit its OOP philosophy
...
In C++, a structure can have both variables and functions as members
...
In C++, the structure names are stand-alone and can be used like any other
type names
...
C++ incorporates all these extensions in another user-defined type known as class
...
Since class is a specially
introduced data type in C++, most of the C++ programmers tend to use the structure for
holding only data, and classes to hold both the data and functions
...
ep
a
itn
Page 117
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Class is a collection of logically related data items and the associated functions which
operate and manipulate those data
...
So, classes are user-defined data types and behave like the built-in types of a
programming language
...
Class,
being a user-defined data type, we can create any number of variables for that class
...
Specifying a class
Specification of a class consists of two parts
...
The class-name is an identifier
...
The functions and variables are collectively called class-members
...
The two new keywords inside the above specification are – private and public
...
These are followed by colons
...
i
...
, only the member functions can have access
to the private data members and private functions
...
Private data members and
function
itn
Page 118
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
o All the class members are private by default
...
l
Public data members and
functions
o If both the labels are missing, then, by default, all the members will be
private and the class will be completely inaccessible by the outsiders
(hence it won’t be useful at all)
...
Generally, data within a class is made private and
the functions are public
...
However, it is not always necessary that
the data must be private and functions public
...
Example of a class
itn
Page 119
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Creating Objects
Once a class has been specified (or declared), we can create variables of that type (by
using the class name as datatype)
...
The above statement creates a variable t1 of type Test
...
So, t1 is called object of class Test
...
Test t1, t2, t3;
When object is created, the necessary memory space is allocated to this object
...
Objects can be
created when a class is defined, as follows:
class Employee
{
int id;
char name[20];
public:
void getname();
void putname();
}e1,e2,e3;
The objects are also called instances of the class
...
l
class Test
{
int x,y;
public:
void get_data()
{
cin>>x>>y;
}
void put_data()
{
cout<
};
Accessing class members
The class members are accessed using a dot operator
...
The dot operator is called member access operator
...
class-member ;
For public data members (if any), we can use following syntax to access them
...
data-member ;
eg
...
data1 = obj1
...
data3;
In the above example, obj1 is an object of class
...
For public functions, we can use following format to call them
class-object
...
e1
...
Here, no arguments have been listed since the function does not take any argument
...
Eg
...
x = 0; //generates error since x is private and can be accessed only thro’
member functions
obj1
...
fu1(); //generates error since fu1() is private
obj1
...
csitnepal
...
o outside the class
o inside the class
The code for the function body would be identical in both the cases
...
l
Defining member functions (i
...
writing the body of a function):
Outside the class
In this approach, the member functions are only declared inside the class, whereas its
definition is written outside the class
...
General form:
return-type class-name::function-name(argument-list)
{
--------- - - - - - - -- - //function body
- - - -- - -- -}
The function is, generally, defined immediately after the class-specifier
...
This symbol is called the scope resolution
operator
...
Eg
...
The scope-resolution operator tells that the function “getdata()” is a
member of the class “Employee”
...
itn
Page 121
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Inside the class
Function body can be included in the class itself by replacing function declaration by
function definition
...
Hence, all
the restrictions that apply to inline function, will also apply here
...
These classes can use same
function name
...
- Member functions can directly access private data of that class
...
(Exception is friend function)
- A member function can call another member function directly, without using
the dot operator
...
class A
{
int a,b;
public:
void getdata()
{
cin>>a>>b;
}
};
Here, getdata() is defined inside the class
...
A function defined outside the class can also be made ‘inline’ simply by using the
qualifier ‘inline’ in the header line of a function definition
...
class A
{
----- ------------ public:
void getdata(); // function declaration inside the class
};
inline void A::getdata()
{
//function body
}
Function definition with the ‘inline’
qualifier/keyword
...
However, a member function can be called by using its name inside another member
function of the same class
...
Eg
...
h>
ep
a
itn
Page 122
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
class Addition
{
int a,b,sum;
public:
void read();
void show();
int add();
};
void Addition::read()
{
cout<<”Enter a and b”;
cin>>a>>b;
}
void Addition::add()
{
return(a+b);
}
void Addition::show()
{
sum=add(); // nesting of function i
...
cout<
main()
{
Addition a1;
a1
...
show( );
return(0);
}
The output of this program will be as follows:
Enter a and b: 2
3
Sum of a and b is:5
Private Member Functions
As we have seen, member functions are, in general, made public
...
Private member functions
can only be called by another function that is a member of its class
...
Eg
...
csitnepal
...
No object used
...
a1
...
Memory Allocation for Objects
- As in the case of structures, memory space for objects is allocated when they
are declared and not when the class is specified
...
The member functions are created and placed
in the memory only once, when they are defined as a part of a class
specification
...
- However, the data members will hold different values for different object
...
Object1
Object2
Object3
datamember1
datamember2
…
...
datamemberN
datamember1
datamember2
…
...
csitnepal
...
...
Since a class is also a user defined data type, we
can create array of objects (the variable of type class)
...
For eg
...
If we have to
keep records of 20 employees in an organization having two departments, then instead of
creating 20 separate variables, we can create array of objects as follows
...
Since the array of objects is an array, we can access the members of the classes as
follows:
dept1[0]
...
getdata();
Objects as function arguments
Like any other variable, objects can also be passed to the function, as an argument
...
- pass by value
- pass by reference
In the “pass by value”, the copy of the object is passed to the function
...
On the other hand,
address of the object is passed in the case of pass by reference
...
The second method is
considered more efficient
...
csitnepal
...
class Height
{
int feet;
int inches;
public:
void getHeight()
{
cout<<”Enter height in feet and inches”;
cin>>feet>>inches;
}
void putHeight()
{
cout<<”Feet:”<
void sum(Height,Height);
};
void Height::sum(Height h1, Height h2)
{
inches = h1
...
inches;
feet=inches/12;
inches=inches%12;
feet=feet + h1
...
feet;
}
int main()
{
Height h1,h2,h3;
h1
...
getHeight();
h3
...
putHeight();
cout<<”Height 2:”<
...
putHeight();
return(0);
}
In the above program, the function sum() takes two objects as arguments
...
Eg
...
csitnepal
...
inches = h1
...
inches;
h3
...
inches / 12;
h3
...
inches % 12;
h3
...
feet + h1
...
feet;
return (h3); //object of type height returned
}
The above function will return an object h3 at the end of its execution
...
In other words, a friend function is a non-member function that has access to the private
members of the class
...
- Since, friend function is not a part of the class, it can be declared anywhere in
the public, private and protected section of the class
...
- It is called like a normal function without the help of any object
...
So, it has
to use an object name and dot operator with each member name (like A
...
A friend function is declared as follows:
class A
{
- - - - - - - - - - -- - - - - - - - - - - - - - - -- - - - - public:
----------------------------------friend void abc(void);
};
//friend function declaration
The declaration is preceded by the keyword “friend”
...
Eg
...
csitnepal
...
n1 + a
...
getn();
cout<<”Mean:”< //friend function called
return(0);
}
Suppose we want a function to operate on objects of two different classes
...
In this situation there is nothing like a friend function
...
Read program
carefully!!!!!!!!
#include
...
h>
class beta; // needed for frenfunction declaration
ep
a
itn
Page 128
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
class alpha
{
private:
int data;
public:
void get_data()
{
cin>>data;
}
friend int frenfunction(alpha, beta); // friend function
};
class beta
{
private:
int data;
public:
void get_data()
{
cin>>data;
}
friend int frenfunction(alpha, beta); // friend function
};
int frenfunction(alpha a,beta b)
{
return(a
...
data);
}
main()
{
alpha aa;
beta bb;
aa
...
get_data();
cout< getch();
return 0;
}
Static Data Members
We have known that, each object of a class maintain their own copy of member data
...
This can be made possible by using static variables
...
- It is visible only within the class, but its lifetime is the entire program
...
- Also known as class variable
...
class A
{
ep
a
itn
Page 129
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
static int count;
int variable;
public:
A()
{
count++;
}
void get_var()
{
cin>>variable;
}
void put_var()
{
cout< }
definition
...
{
cout<
...
};
int A::count;
int A::count=10;
will assign count the initial value 10
main()
{
A a,b,c;
a
...
put_count();
c
...
Properties of static functions are
- they can access only other STATIC members (functions or variables) declared
in the same class
- they can be called using class name
eg
...
csitnepal
...
is :”< }
static void put_count()
//static function accessing static member
{
cout< }
};
int A::count;
main()
{
A a1,a2;
a1
...
set_no();
A::put_count();
a1
...
set_no();
A::put_count();
a1
...
put_no();
return(0);
}
itn
Page 131
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Check output of this program
...
In all the cases, we
have used member functions such as input() and output() to provide initial values to the
private member variables
...
input();
invokes the member function input(), which assigns the initial values to the data items of
object t
...
input(100,200);
passes the initial values as arguments to the function input(), where these values are
assigned to the private variables of object t
...
These functions can not be
used to initialize the member variables at the time of creation of their objects
...
This means that we should be able to initialize a class type
variable (object) when it is declared, much the same way as initialization of an ordinary
variable
...
67;
are valid initialization statements for basic data types
...
But it has not happened with the objects we have so far studied
...
C++ provides a special member function called the constructor which enables an object
to initialize itself when it is created
...
It also provides another member function called the destructor that destroys the objects
when they are no longer required
...
It has the name same as that of class name
...
It is called constructor because it constructs the
values of data members of the class
...
csitnepal
...
They execute automatically when an object of a class is created
...
They should be declared in the “public” section
...
Like C++ functions, they can have default arguments
...
There are, basically, three types of constructors
...
There are
three possible situations for this
...
If we do not provide any constructor with a class, the compiler provided one
would be the default constructor
...
class A
{
//no constructor
};
5
...
class A
{
A()
{}
//or
A(void)
{}
};
Parameterized Constructor
itn
Page 133
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
6
...
class A
{
A (int x=5)
{}
};
A constructor that takes arguments is called a parameterized constructor
...
This can be done in two ways
...
class A
{
int m,n;
public:
A(int x, int y); //parameterized constructor
{
m=x;
n=y;
}
-
-
};
main()
{
Class name
Object name
A obj1(10,20); //implicit call
A obj2 =A(10,20); //explicit call
Constructor call with parameter
-
-
-
}
NOTE: Constructor functions can also be defined explicitly using scope resolution
operator
...
Eg
...
The above statement can also be written as,
itn
Page 134
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
The process of initializing through a copy constructor is known as copy initialization
...
We cannot pass the argument by value to a copy constructor
...
Remember the
statement
obj2 = obj1;
will not invoke the copy constructor
...
This is the task of the overloaded assignment operator (=)
...
class Data
{
int info;
public:
Data()
{}
Data(int a)
// parameterized constructor
{
info
}
Data(Data &x) // copy constructor
{
info=x
...
Data d2(d1); //copy constructor is called here
...
Data d4;
d4 = d1; // copy constructor not called
cout<<”An info stored in d1”;
d1
...
display();
itn
Page 135
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
d3
...
display();
return(0);
}
Constructors are called thrice in this program
...
Similarly, when more than one constructor is defined in a class, it is called
constructor overloading
...
The first one is
invoked when we don’t pass any arguments
...
Eg
...
Data obj2(5); invokes 2nd constructor
Data obj3(obj2); invokes 3rd constructor
Constructor with default argument
Like functions, constructors can also have default arguments
...
class A
{
int a,b,c;
pulic:
A()
{
a=0
}
A(int x,int y=10,int z=20)
{
a=x;b=y;c=z;
}
void display()
{
cout<};
itn
Page 136
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
}
main()
{
A obj1;
A obj2(5,10,15);
A obj3(6);
obj1
...
display();
obj3
...
The second one has default parameters
...
These constructors have all
the properties of the functions with default argument
...
The default argument constructor can be called
with either one argument or no arguments
...
When both these forms are used in a class, it causes ambiguity for a
statement such as
A a;
The ambiguity is whether to call A::A() or A::A(int x = 0)
...
csitnepal
...
h>
#include
...
display();
test t1;
// No argument is passed, so becomes default constructor
t1
...
e
...
The users provide the
values at the run time
...
Eg
...
And we haven’t used the object
l=a;and dot operator
...
csitnepal
...
In other words, they are used to release dynamically allocated memory and
to perform other “cleanup” activities
...
Eg
...
e
...
They are also defined in the public section
...
So, they cannot be overloaded
...
h>
#include
...
csitnepal
...
Programs can
be designed to perform the read and write operations on these files
...
Data transfer between the console unit and the program
...
Data transfer between the program and a disk file
...
It uses file streams as an interface between the programs and the
files
...
In other words, the input
stream extracts (or reads) data from the file and the output stream inserts (or writes) data
to the file
...
Similarly, the output operation involves establishing an output
stream with the necessary links with the program and the output file
...
csitnepal
...
These include ifstream, ofstream and fstream
...
These classes, designed to
manage the disk files, are declared in fstream and therefore we must include this file in
any program that uses files
...
stream classes for file I/O operations
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files
...
A file stream can be
defined using the classes ifstream, ofstream, and fstream
...
A
file can be opened in two ways
3
...
Using the member function open() of the class
Opening Files Using Constructor
Opening a file using constructor involves the following steps:
Page 141
itn
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
ofstream file(“student”); //write only
ifstream file(“employee”); // read only
cs
For example:
l
3
...
That is
to say, the class ofstream is used to create the output stream and the class
ifstream to create the input stream
...
Initialize the file object with the desired filename
...
h>
#include
...
h>
void main()
{
char name[20];
int age;
char sec;
ofstream ofile("Student
...
close();
ifstream ifile("student
...
close();
getch();
}
When a file is opened for writing only, a new file is created if there is no file of that
name
...
Opening Files Using open()
The function open() can be used to open multiple files that use the same stream object
...
This
is done as
file-stream-class
stream-object;
stream-object
...
csitnepal
...
h>
#include
...
h>
main()
{
char name[20];
int age,salary;
char sec;
ofstream ofile;
ofile
...
txt");
cout<<"\nEnter name, age section: ";
cin>>name>>age>>sec;
ofile< ofile< ofile< ofile
...
open("teacher
...
close();
getch();
}
File Modes with open()
The open function can take two arguments, the second one for specifying the file mode
...
open(“filename”, mode);
The second argument (called file mode parameter) specifies the purpose for which the
file is opened
...
put() and get() Functions
The function put() writes a single character to the associated stream
...
ep
a
itn
Page 143
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
h>
#include
...
open("myfile
...
get(ch);
while(ch != '\n')
{
file
...
get(ch);
}
file
...
open("myfile
...
get(ch);
cout< }
file
...
This means that the values are stored in the disk file in the same format in
which they are stored in the internal memory
...
But a 4 digit int will take four
bytes to store it in the character form
...
The first is the address of the variable, and the second is the length of that variable in
bytes
...
ep
a
itn
Page 144
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//writing array of integers using write()
#include
...
h>
#include
...
open("myfile
...
write((char*)&x,sizeof(x));
file
...
open("myfile
...
read((char*)&x,sizeof(x));
for(i = 0;i < 4;i++)
cout<
getch();
}
Writing and Reading Class Objects (Object I/O)
When writing an object we generally want to use binary mode
...
The binary input output functions
write() and read() are used for this
...
h>
#include
...
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
{
cin>>name>>age;
}
void showData()
{
cout< }
};
main()
{
person p,q;
fstream file;
file
...
dat",ios::out|ios::binary);
cout<<"\nEnter person's data: ";
p
...
write((char *)(&p),sizeof(p));
file
...
open("person
...
read((char *)(&q),sizeof(q));
q
...
csitnepal
...
csitnepal
...
h>
#include
...
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
{
cin>>name>>age;
}
void showData()
{
cout< }
};
main()
{
char ch;
person p;
fstream file;
file
...
dat",ios::out|ios::in|ios::binary);
do
{
cout<<"\nEnter person's data: ";
p
...
write((char *)(&p),sizeof(p));
cout<<"Enter another person? ";
cin>>ch;
}while(ch == 'y');
file
...
read((char *)(&p),sizeof(p));
while(!file
...
showData();
file
...
These are also called the current get position and the current put position, or
simply the current position
...
The seekg() and tellg() functions allow us to set and
examine the get pointer, and the seekp() and tellp() functions perform these same actions
on the put pointer
...
The argument
to these functions represents the absolute position in the file
...
The refposition takes one of the
following three constants defined in the class ios
ios :: beg
ios :: cur
ios :: end
start of file
current position of the pointer
end of the file
...
If file is an object of ofstream, then some some
sample pointer offset calls and their actions are:
Action
go to start
stay at the current position
go to the end of file
...
csitnepal
...
h>
#include
...
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
ep
a
Seek call
file
...
seekg(0,ios::cur);
file
...
seekg(m,ios::beg);
file
...
open("group
...
seekg(0,ios::end);
int endposition = file
...
seekg(pos);
file
...
showData();
cout<<"\nRecords in file are:\n";
file
...
read((char*)&p,sizeof(p));
while(!file
...
showData();
file
...
close();
getch();
return 0;
}
ep
a
itn
Page 148
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
// File copy program
...
#include
...
h>
#include
...
h>
void main()
{
char ch;
fstream file1,file2;
file1
...
txt",ios::out|ios::in);
file1<<"welcome to object oriented programming";
file1
...
open("test1
...
open("test2
...
get(ch);
ch = toupper(ch);
file2
...
close();
file2
...
open("test2
...
get(ch);
cout< }
file2
...
Some functions are
good()
returns true if end of file is encountered while reading, otherwise return
returns true when an input or output operation has failed
...
returns true if no error has occurred
...
csitnepal
...
h>
#include
...
h>
void main()
{
char ch;
fstream file;
file
...
txt",ios::in); // read only
if(file
...
fail()
bad()
}
else
{
while(file)
{
file
...
close();
}
getch();
}
itn
Page 150
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
#include
...
h>
#include
...
open("myfile
...
good())
{
cout<<"\nCould not open the file";
}
else
{
while(file)
{
file
...
close();
}
getch();
}
Functions
A function is a single comprehensive unit that performs a specified task
...
Functions break large programs into
smaller tasks
...
Like in C, C++ programs also should contain a main function, where the program always
begins execution
...
When a function is called, control is transferred to the first statement of the function
body
...
Function Prototype (Function declaration)
Function prototype lets the compiler know the structure of function in terms of its name,
number and type of arguments and its return type
...
We call a function as follows
...
,argument n);
Function Definition
Function definition is a process of defining how it does what it does or in other words,
during function definition, we list the series of codes that carry out the task of the
function
...
, datatype n var n)
{
……………… ;
…………………
...
;
}
Default Arguments
In C++, a function can be called without specifying all its arguments
...
The function declaration must provide default values for
those arguments that are not specified
...
ep
a
itn
Page 151
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
0);
main()
{
float rate, i1,i2,i3;
int pr , yr;
cout<<”Enter principal, rate and year”;
cin>>pr>>rate>>yr;
i1=interest(pr ,yr ,rate);
i2=interest(pr , yr);
i3=interest(pr);
cout< return(0);
}
float interest(int p, int t, float r)
{
return((p*t*r)/100);
}
In the above program, t and r has default arguments
...
Only the trailing arguments can have default values
...
We cannot provide a default value to a particular argument at the middle of an
argument list
...
For eg
...
Inline Functions
itn
Page 152
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
C++ has a solution for this problem
...
When a function is defined as inline, compiler copies it s body where the function call is
made, instead of transferring control to that function
...
Eg
...
However, every time a function
is called, it takes a lot of extra time in executing a series of instructions
...
When a
function is small, considerable amount of time is spent in such overheads
...
The compiler may not always accept this request
...
Eg
...
h>
inline float lbtokg(float lbs)
{
return (0
...
When do we use default argument? Explain with example
...
csitnepal
...
i
...
function overloading is the process of using the
same name for two or more functions
...
The number, type or sequence of parameters for a function is called the
function signature
...
Two functions differing only in their return type can not be
overloaded
...
A best match must be
unique
...
#include
...
0)< cout<<”Perimeter of a rectangle: ”< cout<<”Perimeter of a triangle: ”< return (0);
}
ep
a
itn
Page 154
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//function definition
float perimeter(float r)
{
return(2*3
...
The output will be as
follows:
Perimeter of a circle 12
...
It defines
the problem in terms of itself
...
so that the smaller problem is easy to solve
and in the most case they can be solved easily
...
C++ support
such function and these function are called recursive functions
For example: to find the factorial of a given number
Int mani()
{
int num;
cout<<”Enter a number”;
cin>>num;
int f=fact(num);
cout>>”the factorial of given number is”< getch();
return 0;
}
itn
Page 155
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
int fact(int num)
{
If(num==0)
Return 1;
Else
Return (num*fact(num-1));
}
Inheritance
Inheritance is the most powerful feature of object-oriented programming
...
The class inherits all the capabilities of the base class but can add refinements of
its own
...
Inheritance is also called a ‘kind of relationship’
...
Once a class has been written and tested, its features can be adapted by
other programmers whenever required
...
Inheritance
itn
Page 156
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Types
There are 5 types of inheritance
1) Single Inheritance – when a class is derived from only one base class, then it is called
single inheritance
...
// body part
…
}
public:
{
…
...
}
};
class B : public A // derived class B
{
……
…
...
It can be represented as,
Base class A
Base class B
itn
Page 157
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Derived class C
Egclass A
{
……
...
……
};
class C : public A, public B
{
……
...
3) Hierarchical Inheritance: When two or more than two classes are derived from one
base class, it is called hierarchical inheritance
...
csitnepal
...
………
...
……
};
class C : public A
{
………
ep
a
B
………
};
Here two classes B and C are derived from same base class A
...
g
...
…
...
……
};
class C : public B
{
…
...
};
In this example class B is derived from base class A and class C is derived from derived
class B
...
csitnepal
...
gclass student
{
……
…
...
……
...
};
class result : public test, public sport
{
……
…
...
The class test and sport are derived from
student and class result is derived from both test and sport classes
...
itn
Page 160
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Sub-class Definition
A subclass can be defined by specifying its relationship with base class along with its
own details
...
………
};
baseclass-name
The colon indicates that the inheritance has been used
...
e
...
The visibility mode specifies whether the features of the base class are
derived privately, publicly or protectedly
...
The three visibility modes are
public
private
protected
When the base class is publicly inherited, all the public members of the base class
become public members of the derived class
...
All the protected members become protected members of the
derived class
...
So, these can not be accessed
outside the class directly through the derived class object, but might be accessed through
public functions in the derived class
...
NOTE: private members can not be inherited at all
...
When a member is defined with protected access specifier, these members can be
accessed from that class and also from the derived class of this base class
...
i
...
protected members act as public for
derived class and private for other classes
...
csitnepal
...
Consider the program
#include
...
This means, like a
private inheritance, these members can not be directly accessed through object of the
derived class
...
Whereas, unlike a private
inheritance, they can still be inherited and accessed by subsequent derived classes
...
class aclass
{
public:
void disp(void)
{
cout<<”Base”< }
};
class bclass : public aclass
{
public:
void disp(void)
{
cout<<”Derived”< }
};
void main()
{
bclass Bvar;
Bvar
...
If the function is invoked from an object of the derived class, then the function in
the derived is executed
...
Ambiguities in Multiple Inheritance
When a class inherits from multiple base classes, a whole part of ambiguities creep in
...
csitnepal
...
h>
class base1
{
public:
void disp(void)
{
cout<<”Base1”< }
};
class base2
{
public:
void disp(void)
{
cout<<”Base2”< }
itn
Page 163
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Here, the reference to disp() is ambiguous because the compiler does not know whether
disp() refers to the member in class base1 or base2
...
base1::disp();
Dvar
...
That is, the members can be
redefined in the derived class
...
};
class derived : public base1, public base2
{
public:
void disp(void)
{
base1::disp();
base2::disp();
cout<<”Derived class”< }
};
void main()
{
derived Dvar;
Dvar
...
disp(); // Ambiguous
}
}
Another ambiguity that arises in multiple inheritance is the possibility of the derived class
having multiple copies of the same base class
...
B and C in
turn are derived from class A
...
There are two ways of resolving this ambiguity
...
Containership
When a class contains object of another class as its member data, it is termed as
containership
...
Containership
is also termed as “class within class”
...
A obj1;
…
...
So
B is the container class
...
csitnepal
...
Containership is useful with classes that act like a data type
...
l
‘containership’ is also called ‘has-a’ relationship
...
This is
because B has all the characteristics of A, and in addition some of its own
...
itn
Page 165
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
class Manager
{
char name[20];
int age;
public:
void getdata()
{
cin>>name>>age;
}
void putdata()
{
cout< }
};
class Employee // Employee is container class
{
char department[20];
Manager m; // Object of class Manager
public:
void getdata()
{
m
...
putdata();
cout< }
};
void main()
{
Employee e;
e
...
putdata();
getch();
}
Abstract Class
An abstract class is one that is not used to create objects
...
It is a design concept in program development and provides a
base upon which other classes may be built
...
When the same class is
inherited more than once via multiple paths, multiple copies of the base class members
are created in memory
...
A base class inheritance can be specified as a virtual using
the virtual qualifier
...
…
...
…
...
};
class C : public B1, public B2
{
……
……
};
Keywords ‘virtual’ and ‘public’ can be used in either way
...
csitnepal
...
However, if any base
class contains a constructor with one or more arguments, then it is mandatory for the
derived class to have a constructor and pass the arguments to the base class constructors
...
Thus, it
makes sense for the derived class to pass arguments to the base class constructor
...
Since there is only one copy, there is no ambiguity
...
Since the derived class takes the responsibility of supplying initial values to its base
classes, we supply the initial values that are required by all the classes together, when a
derived class object is declared
...
The constructor of the derived class receives the entire list of values as its arguments and
passes them onto the base constructors in the order in which they are declared in the
derived class
...
Example-
ep
a
itn
Page 167
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
5,50,60);
g
...
show_y();
g
...
Since the derived class contains more than one
Constructors and/or Destructors, it becomes confusing which one will be called when
...
This article will clear all this!
Consider the following example program:
// -- INHERITANCE -// Constructors, Destructors
// and Inheritance
#include
...
csitnepal
...
One more example will clear the confusions, if any
...
h>
ep
a
itn
Page 169
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
// base class (1)
class base
{
public:
base(){cout<<"Constructing Base\n";}
~base(){cout<<"Destructing Base\n";}
};
// derived class
// derived form 'base'
class derived1:public base
{
public:
derived1(){cout<<"Constructing Derived1\n";}
~derived1(){cout<<"Destructing Derived1\n";}
};
// derived from a derived class
// 'derived1'
class derived2:public derived1
{
public:
derived2(){cout<<"Constructing Derived2\n";}
~derived2(){cout<<"Destructing Derived2\n";}
};
void main(void)
{
derived2 obj;
// do nothing else, only
// construct and destruct
// the inherited class object
}
OUTPUT:
Constructing Base
Constructing Derived1
Constructing Derived2
Destructing Derived2
Destructing Derived1
Destructing Base
itn
Page 170
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Lab Sheet - 3
Employee
Name
ID
getdata()
putdata()
Manager
ComputerOperator
Department
Typing_Speed
getdata()
putdata()
getdata()
putdata()
7
...
Also write a
main() function to test the classes, Manager and ComputerOperator, by creating
their objects, taking input and displaying the corresponding values
...
Imagine a college hires some lecturers
...
Create a class called lecturer that stores the
ID, and the name of lecturers
...
Each of these three classes should have a readdata() function to get its
data from the user, and a printdata() function to display its data
...
9
...
Create a class Automobile that stores production
date and price
...
Each
of these classes should have member functions to get data and set data
...
itn
Page 171
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
10
...
From this class derive two classes: Bowler and Batsman
...
Use appropriate member functions
in all classes to read and display respective data
...
Define a base class Shape having data member radius (int)
...
Write methods to compute the area of
circle and sphere
...
csitnepal
...
Create classes Book having data members name of author (string), price (float)
and class Stock having data members number of books (int) and category (string)
...
All the classes should have functions having same name
...
Namespace
Namespaces allow to group entities like classes, objects and functions under a name
...
The
format
of
namespaces
is:
namespace
{
entities
}
identifier
Where identifier is any valid identifier and entities is the set of classes, objects and
functions that are included within the namespace
...
In order to access these variables from outside the
”myNamespace” namespace we have to use the scope operator ::
...
1416;
}
ep
a
itn
Page 173
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
int main () {
cout << first::var << endl;
cout << second::var << endl;
return 0;
}
In this case, there are two global variables with the same name: var
...
No redefinition errors happen thanks to
namespaces
...
Example program2
#include
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
namespace second
{
double x = 3
...
7183;
}
itn
Page 174
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
int main () {
using namespace first
cout << x << endl;
cout << y << endl;
using namespace second
cout< cout< return 0;
}
Operator Overloading
The concept of overloading can be applied to operators as well
...
It provides a flexible option for
the operations of new definitions for most of the C++ operators
...
In general,
a = b + c; works only with basic types like ‘int’ and ‘float’, and attempting to
apply it when a, b and c are objects of a user defined class will cause complaints from the
compiler
...
There are two types of operator overloading
Unary operator overloading and
Binary operator overloading
Unary operator overloading
Unary operators are those operators that act on a single operand
...
The following program overloads the ++ unary operator for the distance class
to increment the data number by one
...
csitnepal
...
display();
}
In the above example, the ++ unary operator has been overloaded in the function void
Distance :: operator ++(void)
...
This function is called at the second line ‘++dist’ in the main
...
list)
{
//func body
}
The keyword ‘operator’ is used to overload an operator
...
//Another Example - overloading unary minus operator
class abc
{
int x,y,z;
public:
void getdata(int a,int b,int c)
{
x = a;
y = b;
z = c;
}
void display()
{
cout< }
void operator -();
};
void abc::operator-()
{
x = -x;
y = -y;
z = -z;
}
main()
{
ep
a
itn
Page 176
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
abc a;
a
...
display();
-a;
a
...
If we use a statement like this
c1 = ++c2;
For this we have to define the ++ operator to have a return type object of a class in the
operator++ function
...
the example given
below illustrates this
...
csitnepal
...
put_count();
c2
...
put_count();
c2
...
What about postfix, where the
variable is incremented after its value is used in the expression?
c1++
to make both versions of the increment operator work, we define two overloaded ++
operators as follows
class Counter
{
int count;
public:
Counter()
{
count = 0;
}
Counter(int c)
{
count = c;
}
Counter operator++()
{
return Counter(++count);
}
Counter operator++(int)
{
return Counter(count++);
}
void put_count()
{
cout< }
};
main()
{
ep
a
itn
Page 178
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Counter c1,c2,c3;
c1
...
put_count();
c2 = ++c1;
c3 = c2++;
c1
...
put_count();
c3
...
The one, for
prefix notation, is
Counter operator ++()
The one, for postfix notation, is
Counter operator ++(int)
The only difference is the int in the parentheses
...
It’s simply a signal to the compiler to create the postfix version of
the operator
...
Overloading binary operators
Binary operators are those that work on two operands
...
Overloading a binary operator is similar to overloading unary operator except that a
binary operator requires an additional parameter
...
It adds two objects of type ‘distance’
...
csitnepal
...
meter;
int cm = centimeter + d2
...
getDist();
d3 = d1 + d2; // Invokes operator+() function
d4 = d3
...
show();
d4
...
The argument on the left side the operator (d1 here) is the
object of which the operator is a member
...
Overloading Binary Operators Using Friend Function
ep
a
itn
Page 180
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Friend functions may be used in the place of member functions for overloading a binary
operator, the only difference being that a friend function requires two arguments to be
explicitly passed to it, while a member function requires only one
...
csitnepal
...
meter + d2
...
centimeter + d2
...
getDist();
d3 = d1 + d2;
d3
...
feet && inch == e
...
csitnepal
...
4);
equal e2(6,4
...
h>
#include
...
h>
#define SZ 20
class string
{
private:
char str[SZ];
public:
string()
{
strcpy(str," ");
}
string(char s[])
{
strcpy(str,s);
}
void getstring()
{
cout<<"\nEnter a string ";
cin>>str;
}
int operator ==(string ss)
{
return(strcmp(str,ss
...
csitnepal
...
getstring();
if(s3 == s1)
cout<<"\nYou typed Nepal";
else if(s3 == s2)
cout<<"\nYou typed Kathmandu";
else
cout<<"\nNot of both";
getch();
return 0;
}
//Overloading + operator to concatenate two strings
#include
...
h>
#include
...
str) < SZ)
{
strcpy(temp
...
str,ss
...
csitnepal
...
display();
s2
...
display();
cout< getch();
return 0;
}
//Overloading < operator
class line
{
int feet;
float inch;
public:
line()
{}
line(int f,float i)
{
feet = f;
inch = i;
}
void display()
{
cout< }
int operator<(line);
};
int line::operator<(line l)
{
float l1 = feet + inch/12;
float l2 = l
...
inch/12;
if(l1 return 1;
else
return 0;
}
main()
{
ep
a
itn
Page 185
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
line l1(2,5
...
3);
if(l1 l1
...
display();
getch();
return 0;
}
Multiple Overloading
We have seen several different uses of + operator: - to add distance and to concatenate
strings
...
It selects the correct function to carry out the addition
based on the type of operand
...
ep
a
itn
Page 186
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
h>
#include
...
meter;
int cm = centimeter + d2
...
str) < SZ)
{
strcpy(temp
...
str,ss
...
csitnepal
...
getDist();
d3 = d1 + d2;
d3
...
display();
s2
...
display();
getch();
return 0;
}
General rules for overloading operators
There are some restrictions and limitations to be kept in mind while overloading
operators
...
New operators can not be created
...
It is not recommended to change the basic meaning of an operator
...
Overloaded operators follow syntax rules of the original operators
...
Friend functions can not be used to overload certain operators like =, ( ), [ ] and >
...
But those overloaded by a friend
functions take one reference argument
...
Binary operators such as +, -, *, and / must explicitly return a value
...
itn
Page 188
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Operator Overloading Restriction
Operator functions can not have default arguments
...
*, ?:, sizeof
...
Type Conversion (Data Conversion)
We use the assignment operator (=) to assign value of one variable to another
...
We have also noticed that = assigns the value of one
user defined object to another, provided that they are of the same type
...
The compiler
does not need any special instructions to use = for the assignment of user-defined objects
such as distance objects
...
But if the variables on different sides of the = are of different types, then the type of
variable on the right side of = needs to be converted to the type of left side variable
before the assignment takes place
...
Conversion Between Basic Types
Consider the statement,
intvar = floatvar;
where intvar is of type int and floatvar is of type float
...
There are many such
conversions: from float to double, char to float and so on
...
Such conversions are implicit conversion
...
For example,
ep
a
itn
Page 189
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
int total = 400;
float avg;
avg = float(total) / 5; // converts value of total to float before division takes place
...
Instead, we must write these routines
ourselves
...
These are sometimes
called conversion constructors
...
display();
getch();
}
From User-Defined to Basic Type
When class type data is converted into basic type data, it is called class to basic type
conversion
...
This type of
conversion takes place in casting operator
...
The syntax of casting operator function is
ep
a
itn
Page 190
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
operator typename()
{
………
...
}
This function converts a class type data to typename
...
The operator int() converts a class type object to
type int and so on
...
It must not specify a return type
...
class Stock
{
int items;
float price;
public:
Stock(int a,float p)
{
items = a;
price = p;
}
void putdata()
{
cout<<"Items: "< cout<<"Price: "< }
operator float()
{
return (items*price);
}
};
main()
{
Stock s(45,2
...
putdata();
cout<<"Total float value = "< getch();
return 0;
itn
Page 191
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
}
Another example
class DistConv
{
private:
int kilometers;
double meters;
static double kilometersPerMile;
public:
// This function converts a built-in type (i
...
miles) to the
// user-defined type (i
...
DistConv)
DistConv(double mile) // Constructor with one argument
{
double km = kilometersPerMile * mile ; // converts miles to
//kilometers
kilometers = int(km);
// converts float km to
//int and assigns to kilometer
meters = (km - kilometers) * 1000 ; // converts to meters
}
DistConv(int k, float m) // constructor with two arguments
{
kilometers = k ;
meters = m ;
}
// ********Conversion Function************
operator double()
// converts user-defined type i
...
// DistConv to a basic-type
{
// (double) i
...
meters
double K = meters/1000 ;
// Converts the meters to
// kilometers
K += double(kilometers) ;
// Adds the kilometers
return K / kilometersPerMile ; // Converts to miles
}
void display(void)
{
cout << kilometers << " kilometers and " << meters << " meters" ;
}
}; // End of the Class Definition
double DistConv::kilometersPerMile = 1
...
csitnepal
...
0 ;
// Uses the constructor with one argument
DistConv d2( 2, 25
...
255 kilometers = " << ml << " miles\n" ;
ml = d1 ;
// This form also uses conversion function
// and converts DistConv to miles
d1
...
255 kilometers = 1
...
72 meters = 5 miles*/
From One Class to Another Class Type
When a data of one class type is converted into data of another class type, it is called
conversion of one class to another class type
...
The class Y type data is
converted to the class X type data and converted value is assigned to the objx
...
This type of conversion is carried out by either constructor or
a conversion function
...
We know that the casting operator function
operator typename()
itn
Page 193
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Now consider a single-argument constructor function which serves as an instruction for
converting the argument’s type to the class type of which it is a member
...
The typename may be a
built-in type or user-defined type one
...
Therefore, when a class needs to be converted, a
casting operator function can be used (i
...
source class)
...
conversion
...
class Kilometers
{
private:
double kilometers;
public:
Kilometers(double kms)
{
kilometers = kms;
}
void display()
{
cout << kilometers << " kilometeres";
}
double getValue()
{
return kilometers;
}
};
itn
Page 194
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
class Miles
{
private:
double miles;
public:
Miles(double mls)
{
miles = mls;
}
void display()
{
cout << miles << " miles";
}
operator Kilometers()
{
return Kilometers(miles*1
...
getValue()/1
...
display();
cout << " = ";
k1
...
display();
cout << " = ";
m2
...
934 kilometeres
100 kilometeres = 62
...
csitnepal
...
csitnepal
...
getcode();
value = p
...
getprice();
}
};
main()
{
clrscr();
invent1 s1(100,5,140
...
putdata();
cout<<"Stock value"<<"\n";
cout<<"value = "< cout<<"Product details-invent2 type"<<"\n";
d1
...
csitnepal
...
Write a program to overload += operator
...
Write a program to overload = operator (It is already overloaded in C++)
...
10
...
11
...
Overload + operator to add two objects of class Length
...
Also facilitate the operations like L4 = L1 + 5 and L5 = 5 + L4 where L1,
L2, L3, L4 and L5 are objects of class Length
...
12
...
Assume that the class distance contains two data members (feet
(integer type) and inch (floating point type)
...
33 feet and 1 feet
= 12 inches)
13
...
e
...
Let P1
and P2 be the objects of this class where P1 is initialized to (20, 30)
...
itn
Page 198
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
14
...
Virtual Function and Run Time Polymorphism
Pointers
Pointers have a reputation for being hard to understand
...
Addresses are numbers, just as they
are for houses on a street
...
If you have 1MB of
memory, the highest address is 1,048,575; for 16 MB of memory, it is 16,777,215
...
New and Delete Operator
Pointer provides the necessary support for C++ powerful dynamic memory allocation
system
...
For eg- int arr[100];
reserves memory for 100 integers
...
We must know at the time we write the program how big the
array will be and it is not always possible to predict what the size of the array will be
...
This capability is provided by the new operator
...
The syntax for the
new operator is
= new ;
where = pointer variable
= char, int, float and so on
type of variable mentioned on the left hand side and the type mentioned on the right hand
side should match
...
csitnepal
...
For egchar *cptr;
cptr = new char[10];
allocates 10 bytes of memory and assigns the starting address to cptr
...
To ensure safe and efficient use of
memory, the new operator is matched by a corresponding delete operator that returns
memory to the operating system
...
However, this address is no longer valid, the memory it
points to may be changed to something entirely different but we do not use pointers
memory that has been deleted
...
For egdelete[] cptr;
//Example program that makes use of new and delete operator
#include
...
h>
class test
{
int x;
public:
void input()
{
cin>>x;
}
void display()
{
cout< }
};
main()
{
test *t = new test;
t->input();
t->display();
delete t;
getch();
return 0;
}
ep
a
itn
Page 200
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Polymorphism
In the programming sphere, polymorphism is broadly divided into two parts- the first part
being static polymorphism- exhibited by overloaded functions and the second being
dynamic polymorphism exhibited by late binding
...
Static polymorphism involves binding of functions on the basis of
number, type, and sequence of their arguments
...
This form of association is called early binding
...
The resolution is on the basis of number, type, and sequence of
arguments declared for each form of the function
...
void add(int, int);
void add(float, float);
Now, if the function add() is invoked, the parameters passed to it will determine which
version of the function will be executed
...
Dynamic Polymorphism
Dynamic polymorphism refers to an entity changing its form depending on the
circumstances
...
The term late binding refers to the resolution of the function to their
associated methods at run time instead of compile time
...
The compiler is unable to bind a call to a method since resolution depends
on the context of the call
...
Virtual Functions
Virtual means existing in appearance but not in reality
...
A function is made virtual by placing the keyword virtual
before its normal declaration
...
ep
a
itn
Page 201
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
...
h>
class Base
{
public:
void show()
{
cout<<"Base\n";
}
};
class Derv1 : public Base
{
public:
void show()
{
cout<<"Derv1\n";
}
};
class Derv2 : public Base
{
public:
void show()
{
cout<<"Derv2\n";
}
};
int main()
{
Derv1 d1;
Derv2 d2;
Base *ptr; // pointer to base class
ptr = &d1;
ptr->show();
ptr = &d2;
ptr->show();
getch();
return 0;
}
itn
Page 202
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Virtual Member Functions Accessed with Pointers
Let’s make a single change in the above program
...
#include
...
h>
l
Output of the program
Base
Base
The function in the base class is always executed
...
class Base
{
public:
virtual void show()
{
cout<<"Base\n";
}
};
class Derv1 : public Base
{
public:
void show()
{
cout<<"Derv1\n";
}
};
class Derv2 : public Base
{
public:
void show()
{
cout<<"Derv2\n";
}
};
int main()
{
Derv1 d1;
Derv2 d2;
Base *ptr;
ptr = &d1;
ptr->show();
ptr = &d2;
ptr->show();
getch();
return 0;
}
Output of the program
Derv1
Derv2
Now, as you can see, the member functions of the derived classes, not the base class, are
executed
...
So the same function call,
ep
a
itn
Page 203
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
ptr->show();
executes different functions, depending on the contents of ptr
...
Here,
the compiler does not know what class the contents of ptr may contain
...
Which version of show()
does the compiler call? In fact the compiler does not know what to do, so it arranges for
the decision to be deferred until the program is running
...
Abstract Classes and Pure Virtual Functions
An abstract class is one that is not used to create objects
...
A class is made an
abstract by placing at least one pure virtual function in the class
...
i
...
a pure virtual function can be
declared by equating it to zero
...
The =0 syntax is simply how we will tell the compiler that a function will be
pure
...
If a class does not
override the pure virtual function, then it becomes an abstract class itself, and we can not
instantiate objects from it
...
We can not create objects of the abstract class
...
This allows an abstract class to be used as a base class, pointers to which
can be used to select the proper virtual function
...
csitnepal
...
h>
#include
...
csitnepal
...
h>
#include
...
csitnepal
...
5) ? 1 : 0;
}
};
class professor : public person
{
private:
int numpubs;
public:
void getData()
{
person :: getName();
cout<<"\nEnter number of publications";
cin>>numpubs;
}
int isOutstanding()
{
return (numpubs > 100)?1 : 0;
}
};
main()
{
person *persptr[100];
int n = 0;
char choice;
do
{
cout<<"\nEnter student or professor(s/p)";
cin>>choice;
if(choice == 's')
persptr[n] = new student;
else
persptr[n] = new professor;
persptr[n++]->getData();
cout<<"\nAnother record? ";
cin>>choice;
}while(choice == 'y');
for(int j = 0;j < n; j++)
{
persptr[j]->putName();
if(persptr[j]->isOutstanding())
cout<<"\nThis person is outstanding";
}
getch();
return 0;
}
Friend class
The member functions of a class can all be made friends at the same time when we make
the entire class a friend
...
#include
...
h>
class alpha
{
int data;
public:
alpha()
{
data = 10;
}
friend class beta; // beta is friend class
};
class beta
{
public:
void func1(alpha a)
{
cout<
...
data;
}
};
main()
{
ep
a
itn
Page 207
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
alpha a;
beta b;
b
...
func2(a);
getch();
return 0;
}
In class alpha the entire class beta is defined as a friend
...
The this Pointer
The member functions of every object have access to a sort of magic pointer named this,
which points to the object itself
...
h>
#include
...
TestThisPointer();
m2
...
The this pointer can be treated like any
other pointer to an object, and can thus be used to access the data in the object it points
to
...
csitnepal
...
test();
getch();
return 0;
}
This program simply prints the value 10
...
csitnepal
...
class alpha
{
int data;
public:
alpha()
{}
alpha(int x)
{
data = x;
}
void display()
{
cout<}
alpha& operator = (alpha &a)
{
data = a
...
display();
l
This is exactly the same as referring to x directly
...
display();
getch();
return 0;
}
ep
a
itn
Page 210
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//using this pointer for returning value from member function
class Distance
{
int meter;
int centimeter;
public:
Distance()
{
meter = 0;
centimeter = 0;
}
Distance (int m, int cm)
{
meter = m;
centimeter = cm;
}
void getDist()
{
cout<<"Enter meter";
cin>>meter;
cout<<"Enter centimeter";
cin>>centimeter;
}
void show()
{
cout< }
Distance compare(Distance);
};
Distance Distance :: compare(Distance d2)
{
float dist1 = meter + (float)centimeter/100;
float dist2 = d2
...
centimeter/100;
if(dist1 < dist2)
return *this;
else
return d2;
}
main()
{
Distance d1(4,50);
Distance d2,d3,d4;
d2
...
compare(d2);
cout<<"Small lenght is: ";
d4
...
csitnepal
...
It supports the generic data types
and generic programming
...
Templates are a feature of the C++ programming language that allows functions and
classes to operate with generic types
...
A template is a way to specify generic code, with a placeholder for the type
...
Templates offer several advantages:
Templates are easier to write
...
Templates can be easier to understand, since they can provide a straightforward
way of abstracting type information
...
Because the types that templates act upon are known at
compile time, the compiler can perform type checking before errors occur
...
However, there are many differences between a macro like this:
#define min(i, j) (((i) < (j)) ? (i) : (j))
and a template:
template T min (T i, T j) { return ((i < j) ? i : j) }
Here are some problems with the macro:
Source: www
...
com (By:Tej Bahadur Shahi)
Page 212
l
ep
a
itn
There is no way for the compiler to verify that the macro parameters are of
compatible types
...
The i and j parameters are evaluated twice
...
Because macros are expanded by the preprocessor, compiler error messages will
refer to the expanded macro, rather than the macro definition itself
...
cs
Templates in c++ comes in two variations
a) function templates
b) class templates
Class template
The relationship between a class template and an individual class is like the relationship
between a class and an individual object
...
The general form of a class template is
Template
Class class_name
{
//class member with type T whenever appropriate
};
Example
#include
...
x = v1
...
y = v1
...
csitnepal
...
9,6
...
0,-2
...
Compiler generates classes for only the used types
...
Templates reduce the effort on coding for different data types to a single set of
code
...
Function template
To perform identical operations for each type of data compactly and conveniently, we use
function templates
...
Based on the
argument types provided in calls to the function, the compiler automatically instantiates
separate object code functions to handle each type of call appropriately
...
When the
compiler sees an instantiation of the function template, for example: the call max(10, 15)
in function main, the compiler generates a function max(int, int)
...
Page 214
itn
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
//function template
cs
template
l
#include
using namespace std ;
//max returns the maximum of the two elements
T max(T a, T b)
{
return a > b ? a : b ;
}
int main()
{
cout << "max(10, 15) = " << max(10, 15) << endl ;
cout << "max('k', 's') = " << max('k', 's') << endl ;
cout << "max(10
...
2) = " << max(10
...
2) << endl ;
return 0;
}
Output:
max(10, 15) = 15
max('k', 's') = s
max(10
...
2) = 15
...
The keyword class, within the angle brackets, might just as well be called type
...
The variable following the keyword class (T in
this example) is called the template argument
...
csitnepal
Title: C++
Description: A simple and easy note is here for u...I can bet u gonna pass any exam with this note...so guys what are you looking for??Download it and enjoy
h>
class beta; // needed for frenfunction declaration
ep
a
itn
Page 128
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
class alpha
{
private:
int data;
public:
void get_data()
{
cin>>data;
}
friend int frenfunction(alpha, beta); // friend function
};
class beta
{
private:
int data;
public:
void get_data()
{
cin>>data;
}
friend int frenfunction(alpha, beta); // friend function
};
int frenfunction(alpha a,beta b)
{
return(a
...
data);
}
main()
{
alpha aa;
beta bb;
aa
...
get_data();
cout<
return 0;
}
Static Data Members
We have known that, each object of a class maintain their own copy of member data
...
This can be made possible by using static variables
...
- It is visible only within the class, but its lifetime is the entire program
...
- Also known as class variable
...
class A
{
ep
a
itn
Page 129
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
static int count;
int variable;
public:
A()
{
count++;
}
void get_var()
{
cin>>variable;
}
void put_var()
{
cout<
definition
...
{
cout<
};
int A::count;
int A::count=10;
will assign count the initial value 10
main()
{
A a,b,c;
a
...
put_count();
c
...
Properties of static functions are
- they can access only other STATIC members (functions or variables) declared
in the same class
- they can be called using class name
eg
...
csitnepal
...
is :”<
static void put_count()
//static function accessing static member
{
cout<
};
int A::count;
main()
{
A a1,a2;
a1
...
set_no();
A::put_count();
a1
...
set_no();
A::put_count();
a1
...
put_no();
return(0);
}
itn
Page 131
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Check output of this program
...
In all the cases, we
have used member functions such as input() and output() to provide initial values to the
private member variables
...
input();
invokes the member function input(), which assigns the initial values to the data items of
object t
...
input(100,200);
passes the initial values as arguments to the function input(), where these values are
assigned to the private variables of object t
...
These functions can not be
used to initialize the member variables at the time of creation of their objects
...
This means that we should be able to initialize a class type
variable (object) when it is declared, much the same way as initialization of an ordinary
variable
...
67;
are valid initialization statements for basic data types
...
But it has not happened with the objects we have so far studied
...
C++ provides a special member function called the constructor which enables an object
to initialize itself when it is created
...
It also provides another member function called the destructor that destroys the objects
when they are no longer required
...
It has the name same as that of class name
...
It is called constructor because it constructs the
values of data members of the class
...
csitnepal
...
They execute automatically when an object of a class is created
...
They should be declared in the “public” section
...
Like C++ functions, they can have default arguments
...
There are, basically, three types of constructors
...
There are
three possible situations for this
...
If we do not provide any constructor with a class, the compiler provided one
would be the default constructor
...
class A
{
//no constructor
};
5
...
class A
{
A()
{}
//or
A(void)
{}
};
Parameterized Constructor
itn
Page 133
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
6
...
class A
{
A (int x=5)
{}
};
A constructor that takes arguments is called a parameterized constructor
...
This can be done in two ways
...
class A
{
int m,n;
public:
A(int x, int y); //parameterized constructor
{
m=x;
n=y;
}
-
-
};
main()
{
Class name
Object name
A obj1(10,20); //implicit call
A obj2 =A(10,20); //explicit call
Constructor call with parameter
-
-
-
}
NOTE: Constructor functions can also be defined explicitly using scope resolution
operator
...
Eg
...
The above statement can also be written as,
itn
Page 134
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
The process of initializing through a copy constructor is known as copy initialization
...
We cannot pass the argument by value to a copy constructor
...
Remember the
statement
obj2 = obj1;
will not invoke the copy constructor
...
This is the task of the overloaded assignment operator (=)
...
class Data
{
int info;
public:
Data()
{}
Data(int a)
// parameterized constructor
{
info
}
Data(Data &x) // copy constructor
{
info=x
...
Data d2(d1); //copy constructor is called here
...
Data d4;
d4 = d1; // copy constructor not called
cout<<”An info stored in d1”;
d1
...
display();
itn
Page 135
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
d3
...
display();
return(0);
}
Constructors are called thrice in this program
...
Similarly, when more than one constructor is defined in a class, it is called
constructor overloading
...
The first one is
invoked when we don’t pass any arguments
...
Eg
...
Data obj2(5); invokes 2nd constructor
Data obj3(obj2); invokes 3rd constructor
Constructor with default argument
Like functions, constructors can also have default arguments
...
class A
{
int a,b,c;
pulic:
A()
{
a=0
}
A(int x,int y=10,int z=20)
{
a=x;b=y;c=z;
}
void display()
{
cout<};
itn
Page 136
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
}
main()
{
A obj1;
A obj2(5,10,15);
A obj3(6);
obj1
...
display();
obj3
...
The second one has default parameters
...
These constructors have all
the properties of the functions with default argument
...
The default argument constructor can be called
with either one argument or no arguments
...
When both these forms are used in a class, it causes ambiguity for a
statement such as
A a;
The ambiguity is whether to call A::A() or A::A(int x = 0)
...
csitnepal
...
h>
#include
display();
test t1;
// No argument is passed, so becomes default constructor
t1
...
e
...
The users provide the
values at the run time
...
Eg
...
And we haven’t used the object
l=a;and dot operator
...
csitnepal
...
In other words, they are used to release dynamically allocated memory and
to perform other “cleanup” activities
...
Eg
...
e
...
They are also defined in the public section
...
So, they cannot be overloaded
...
h>
#include
csitnepal
...
Programs can
be designed to perform the read and write operations on these files
...
Data transfer between the console unit and the program
...
Data transfer between the program and a disk file
...
It uses file streams as an interface between the programs and the
files
...
In other words, the input
stream extracts (or reads) data from the file and the output stream inserts (or writes) data
to the file
...
Similarly, the output operation involves establishing an output
stream with the necessary links with the program and the output file
...
csitnepal
...
These include ifstream, ofstream and fstream
...
These classes, designed to
manage the disk files, are declared in fstream and therefore we must include this file in
any program that uses files
...
stream classes for file I/O operations
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files
...
A file stream can be
defined using the classes ifstream, ofstream, and fstream
...
A
file can be opened in two ways
3
...
Using the member function open() of the class
Opening Files Using Constructor
Opening a file using constructor involves the following steps:
Page 141
itn
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
ofstream file(“student”); //write only
ifstream file(“employee”); // read only
cs
For example:
l
3
...
That is
to say, the class ofstream is used to create the output stream and the class
ifstream to create the input stream
...
Initialize the file object with the desired filename
...
h>
#include
h>
void main()
{
char name[20];
int age;
char sec;
ofstream ofile("Student
...
close();
ifstream ifile("student
...
close();
getch();
}
When a file is opened for writing only, a new file is created if there is no file of that
name
...
Opening Files Using open()
The function open() can be used to open multiple files that use the same stream object
...
This
is done as
file-stream-class
stream-object;
stream-object
...
csitnepal
...
h>
#include
h>
main()
{
char name[20];
int age,salary;
char sec;
ofstream ofile;
ofile
...
txt");
cout<<"\nEnter name, age section: ";
cin>>name>>age>>sec;
ofile<
...
open("teacher
...
close();
getch();
}
File Modes with open()
The open function can take two arguments, the second one for specifying the file mode
...
open(“filename”, mode);
The second argument (called file mode parameter) specifies the purpose for which the
file is opened
...
put() and get() Functions
The function put() writes a single character to the associated stream
...
ep
a
itn
Page 143
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
h>
#include
open("myfile
...
get(ch);
while(ch != '\n')
{
file
...
get(ch);
}
file
...
open("myfile
...
get(ch);
cout<
file
...
This means that the values are stored in the disk file in the same format in
which they are stored in the internal memory
...
But a 4 digit int will take four
bytes to store it in the character form
...
The first is the address of the variable, and the second is the length of that variable in
bytes
...
ep
a
itn
Page 144
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//writing array of integers using write()
#include
h>
#include
open("myfile
...
write((char*)&x,sizeof(x));
file
...
open("myfile
...
read((char*)&x,sizeof(x));
for(i = 0;i < 4;i++)
cout<
getch();
}
Writing and Reading Class Objects (Object I/O)
When writing an object we generally want to use binary mode
...
The binary input output functions
write() and read() are used for this
...
h>
#include
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
{
cin>>name>>age;
}
void showData()
{
cout<
};
main()
{
person p,q;
fstream file;
file
...
dat",ios::out|ios::binary);
cout<<"\nEnter person's data: ";
p
...
write((char *)(&p),sizeof(p));
file
...
open("person
...
read((char *)(&q),sizeof(q));
q
...
csitnepal
...
csitnepal
...
h>
#include
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
{
cin>>name>>age;
}
void showData()
{
cout<
};
main()
{
char ch;
person p;
fstream file;
file
...
dat",ios::out|ios::in|ios::binary);
do
{
cout<<"\nEnter person's data: ";
p
...
write((char *)(&p),sizeof(p));
cout<<"Enter another person? ";
cin>>ch;
}while(ch == 'y');
file
...
read((char *)(&p),sizeof(p));
while(!file
...
showData();
file
...
These are also called the current get position and the current put position, or
simply the current position
...
The seekg() and tellg() functions allow us to set and
examine the get pointer, and the seekp() and tellp() functions perform these same actions
on the put pointer
...
The argument
to these functions represents the absolute position in the file
...
The refposition takes one of the
following three constants defined in the class ios
ios :: beg
ios :: cur
ios :: end
start of file
current position of the pointer
end of the file
...
If file is an object of ofstream, then some some
sample pointer offset calls and their actions are:
Action
go to start
stay at the current position
go to the end of file
...
csitnepal
...
h>
#include
h>
class person
{
protected:
char name[20];
int age;
public:
void getData()
ep
a
Seek call
file
...
seekg(0,ios::cur);
file
...
seekg(m,ios::beg);
file
...
open("group
...
seekg(0,ios::end);
int endposition = file
...
seekg(pos);
file
...
showData();
cout<<"\nRecords in file are:\n";
file
...
read((char*)&p,sizeof(p));
while(!file
...
showData();
file
...
close();
getch();
return 0;
}
ep
a
itn
Page 148
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
// File copy program
...
#include
h>
#include
h>
void main()
{
char ch;
fstream file1,file2;
file1
...
txt",ios::out|ios::in);
file1<<"welcome to object oriented programming";
file1
...
open("test1
...
open("test2
...
get(ch);
ch = toupper(ch);
file2
...
close();
file2
...
open("test2
...
get(ch);
cout<
file2
...
Some functions are
good()
returns true if end of file is encountered while reading, otherwise return
returns true when an input or output operation has failed
...
returns true if no error has occurred
...
csitnepal
...
h>
#include
h>
void main()
{
char ch;
fstream file;
file
...
txt",ios::in); // read only
if(file
...
fail()
bad()
}
else
{
while(file)
{
file
...
close();
}
getch();
}
itn
Page 150
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
#include
h>
#include
open("myfile
...
good())
{
cout<<"\nCould not open the file";
}
else
{
while(file)
{
file
...
close();
}
getch();
}
Functions
A function is a single comprehensive unit that performs a specified task
...
Functions break large programs into
smaller tasks
...
Like in C, C++ programs also should contain a main function, where the program always
begins execution
...
When a function is called, control is transferred to the first statement of the function
body
...
Function Prototype (Function declaration)
Function prototype lets the compiler know the structure of function in terms of its name,
number and type of arguments and its return type
...
We call a function as follows
...
,argument n);
Function Definition
Function definition is a process of defining how it does what it does or in other words,
during function definition, we list the series of codes that carry out the task of the
function
...
, datatype n var n)
{
……………… ;
…………………
...
;
}
Default Arguments
In C++, a function can be called without specifying all its arguments
...
The function declaration must provide default values for
those arguments that are not specified
...
ep
a
itn
Page 151
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
0);
main()
{
float rate, i1,i2,i3;
int pr , yr;
cout<<”Enter principal, rate and year”;
cin>>pr>>rate>>yr;
i1=interest(pr ,yr ,rate);
i2=interest(pr , yr);
i3=interest(pr);
cout<
}
float interest(int p, int t, float r)
{
return((p*t*r)/100);
}
In the above program, t and r has default arguments
...
Only the trailing arguments can have default values
...
We cannot provide a default value to a particular argument at the middle of an
argument list
...
For eg
...
Inline Functions
itn
Page 152
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
C++ has a solution for this problem
...
When a function is defined as inline, compiler copies it s body where the function call is
made, instead of transferring control to that function
...
Eg
...
However, every time a function
is called, it takes a lot of extra time in executing a series of instructions
...
When a
function is small, considerable amount of time is spent in such overheads
...
The compiler may not always accept this request
...
Eg
...
h>
inline float lbtokg(float lbs)
{
return (0
...
When do we use default argument? Explain with example
...
csitnepal
...
i
...
function overloading is the process of using the
same name for two or more functions
...
The number, type or sequence of parameters for a function is called the
function signature
...
Two functions differing only in their return type can not be
overloaded
...
A best match must be
unique
...
#include
0)<
}
ep
a
itn
Page 154
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//function definition
float perimeter(float r)
{
return(2*3
...
The output will be as
follows:
Perimeter of a circle 12
...
It defines
the problem in terms of itself
...
so that the smaller problem is easy to solve
and in the most case they can be solved easily
...
C++ support
such function and these function are called recursive functions
For example: to find the factorial of a given number
Int mani()
{
int num;
cout<<”Enter a number”;
cin>>num;
int f=fact(num);
cout>>”the factorial of given number is”<
return 0;
}
itn
Page 155
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
int fact(int num)
{
If(num==0)
Return 1;
Else
Return (num*fact(num-1));
}
Inheritance
Inheritance is the most powerful feature of object-oriented programming
...
The class inherits all the capabilities of the base class but can add refinements of
its own
...
Inheritance is also called a ‘kind of relationship’
...
Once a class has been written and tested, its features can be adapted by
other programmers whenever required
...
Inheritance
itn
Page 156
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Types
There are 5 types of inheritance
1) Single Inheritance – when a class is derived from only one base class, then it is called
single inheritance
...
// body part
…
}
public:
{
…
...
}
};
class B : public A // derived class B
{
……
…
...
It can be represented as,
Base class A
Base class B
itn
Page 157
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Derived class C
Egclass A
{
……
...
……
};
class C : public A, public B
{
……
...
3) Hierarchical Inheritance: When two or more than two classes are derived from one
base class, it is called hierarchical inheritance
...
csitnepal
...
………
...
……
};
class C : public A
{
………
ep
a
B
………
};
Here two classes B and C are derived from same base class A
...
g
...
…
...
……
};
class C : public B
{
…
...
};
In this example class B is derived from base class A and class C is derived from derived
class B
...
csitnepal
...
gclass student
{
……
…
...
……
...
};
class result : public test, public sport
{
……
…
...
The class test and sport are derived from
student and class result is derived from both test and sport classes
...
itn
Page 160
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Sub-class Definition
A subclass can be defined by specifying its relationship with base class along with its
own details
...
………
};
baseclass-name
The colon indicates that the inheritance has been used
...
e
...
The visibility mode specifies whether the features of the base class are
derived privately, publicly or protectedly
...
The three visibility modes are
public
private
protected
When the base class is publicly inherited, all the public members of the base class
become public members of the derived class
...
All the protected members become protected members of the
derived class
...
So, these can not be accessed
outside the class directly through the derived class object, but might be accessed through
public functions in the derived class
...
NOTE: private members can not be inherited at all
...
When a member is defined with protected access specifier, these members can be
accessed from that class and also from the derived class of this base class
...
i
...
protected members act as public for
derived class and private for other classes
...
csitnepal
...
Consider the program
#include
This means, like a
private inheritance, these members can not be directly accessed through object of the
derived class
...
Whereas, unlike a private
inheritance, they can still be inherited and accessed by subsequent derived classes
...
class aclass
{
public:
void disp(void)
{
cout<<”Base”<
};
class bclass : public aclass
{
public:
void disp(void)
{
cout<<”Derived”<
};
void main()
{
bclass Bvar;
Bvar
...
If the function is invoked from an object of the derived class, then the function in
the derived is executed
...
Ambiguities in Multiple Inheritance
When a class inherits from multiple base classes, a whole part of ambiguities creep in
...
csitnepal
...
h>
class base1
{
public:
void disp(void)
{
cout<<”Base1”<
};
class base2
{
public:
void disp(void)
{
cout<<”Base2”<
itn
Page 163
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Here, the reference to disp() is ambiguous because the compiler does not know whether
disp() refers to the member in class base1 or base2
...
base1::disp();
Dvar
...
That is, the members can be
redefined in the derived class
...
};
class derived : public base1, public base2
{
public:
void disp(void)
{
base1::disp();
base2::disp();
cout<<”Derived class”<
};
void main()
{
derived Dvar;
Dvar
...
disp(); // Ambiguous
}
}
Another ambiguity that arises in multiple inheritance is the possibility of the derived class
having multiple copies of the same base class
...
B and C in
turn are derived from class A
...
There are two ways of resolving this ambiguity
...
Containership
When a class contains object of another class as its member data, it is termed as
containership
...
Containership
is also termed as “class within class”
...
A obj1;
…
...
So
B is the container class
...
csitnepal
...
Containership is useful with classes that act like a data type
...
l
‘containership’ is also called ‘has-a’ relationship
...
This is
because B has all the characteristics of A, and in addition some of its own
...
itn
Page 165
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
class Manager
{
char name[20];
int age;
public:
void getdata()
{
cin>>name>>age;
}
void putdata()
{
cout<
};
class Employee // Employee is container class
{
char department[20];
Manager m; // Object of class Manager
public:
void getdata()
{
m
...
putdata();
cout<
};
void main()
{
Employee e;
e
...
putdata();
getch();
}
Abstract Class
An abstract class is one that is not used to create objects
...
It is a design concept in program development and provides a
base upon which other classes may be built
...
When the same class is
inherited more than once via multiple paths, multiple copies of the base class members
are created in memory
...
A base class inheritance can be specified as a virtual using
the virtual qualifier
...
…
...
…
...
};
class C : public B1, public B2
{
……
……
};
Keywords ‘virtual’ and ‘public’ can be used in either way
...
csitnepal
...
However, if any base
class contains a constructor with one or more arguments, then it is mandatory for the
derived class to have a constructor and pass the arguments to the base class constructors
...
Thus, it
makes sense for the derived class to pass arguments to the base class constructor
...
Since there is only one copy, there is no ambiguity
...
Since the derived class takes the responsibility of supplying initial values to its base
classes, we supply the initial values that are required by all the classes together, when a
derived class object is declared
...
The constructor of the derived class receives the entire list of values as its arguments and
passes them onto the base constructors in the order in which they are declared in the
derived class
...
Example-
ep
a
itn
Page 167
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
5,50,60);
g
...
show_y();
g
...
Since the derived class contains more than one
Constructors and/or Destructors, it becomes confusing which one will be called when
...
This article will clear all this!
Consider the following example program:
// -- INHERITANCE -// Constructors, Destructors
// and Inheritance
#include
csitnepal
...
One more example will clear the confusions, if any
...
h>
ep
a
itn
Page 169
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
// base class (1)
class base
{
public:
base(){cout<<"Constructing Base\n";}
~base(){cout<<"Destructing Base\n";}
};
// derived class
// derived form 'base'
class derived1:public base
{
public:
derived1(){cout<<"Constructing Derived1\n";}
~derived1(){cout<<"Destructing Derived1\n";}
};
// derived from a derived class
// 'derived1'
class derived2:public derived1
{
public:
derived2(){cout<<"Constructing Derived2\n";}
~derived2(){cout<<"Destructing Derived2\n";}
};
void main(void)
{
derived2 obj;
// do nothing else, only
// construct and destruct
// the inherited class object
}
OUTPUT:
Constructing Base
Constructing Derived1
Constructing Derived2
Destructing Derived2
Destructing Derived1
Destructing Base
itn
Page 170
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Lab Sheet - 3
Employee
Name
ID
getdata()
putdata()
Manager
ComputerOperator
Department
Typing_Speed
getdata()
putdata()
getdata()
putdata()
7
...
Also write a
main() function to test the classes, Manager and ComputerOperator, by creating
their objects, taking input and displaying the corresponding values
...
Imagine a college hires some lecturers
...
Create a class called lecturer that stores the
ID, and the name of lecturers
...
Each of these three classes should have a readdata() function to get its
data from the user, and a printdata() function to display its data
...
9
...
Create a class Automobile that stores production
date and price
...
Each
of these classes should have member functions to get data and set data
...
itn
Page 171
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
10
...
From this class derive two classes: Bowler and Batsman
...
Use appropriate member functions
in all classes to read and display respective data
...
Define a base class Shape having data member radius (int)
...
Write methods to compute the area of
circle and sphere
...
csitnepal
...
Create classes Book having data members name of author (string), price (float)
and class Stock having data members number of books (int) and category (string)
...
All the classes should have functions having same name
...
Namespace
Namespaces allow to group entities like classes, objects and functions under a name
...
The
format
of
namespaces
is:
namespace
{
entities
}
identifier
Where identifier is any valid identifier and entities is the set of classes, objects and
functions that are included within the namespace
...
In order to access these variables from outside the
”myNamespace” namespace we have to use the scope operator ::
...
1416;
}
ep
a
itn
Page 173
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
int main () {
cout << first::var << endl;
cout << second::var << endl;
return 0;
}
In this case, there are two global variables with the same name: var
...
No redefinition errors happen thanks to
namespaces
...
Example program2
#include
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
namespace second
{
double x = 3
...
7183;
}
itn
Page 174
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
int main () {
using namespace first
cout << x << endl;
cout << y << endl;
using namespace second
cout<
}
Operator Overloading
The concept of overloading can be applied to operators as well
...
It provides a flexible option for
the operations of new definitions for most of the C++ operators
...
In general,
a = b + c; works only with basic types like ‘int’ and ‘float’, and attempting to
apply it when a, b and c are objects of a user defined class will cause complaints from the
compiler
...
There are two types of operator overloading
Unary operator overloading and
Binary operator overloading
Unary operator overloading
Unary operators are those operators that act on a single operand
...
The following program overloads the ++ unary operator for the distance class
to increment the data number by one
...
csitnepal
...
display();
}
In the above example, the ++ unary operator has been overloaded in the function void
Distance :: operator ++(void)
...
This function is called at the second line ‘++dist’ in the main
...
list)
{
//func body
}
The keyword ‘operator’ is used to overload an operator
...
//Another Example - overloading unary minus operator
class abc
{
int x,y,z;
public:
void getdata(int a,int b,int c)
{
x = a;
y = b;
z = c;
}
void display()
{
cout<
void operator -();
};
void abc::operator-()
{
x = -x;
y = -y;
z = -z;
}
main()
{
ep
a
itn
Page 176
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
abc a;
a
...
display();
-a;
a
...
If we use a statement like this
c1 = ++c2;
For this we have to define the ++ operator to have a return type object of a class in the
operator++ function
...
the example given
below illustrates this
...
csitnepal
...
put_count();
c2
...
put_count();
c2
...
What about postfix, where the
variable is incremented after its value is used in the expression?
c1++
to make both versions of the increment operator work, we define two overloaded ++
operators as follows
class Counter
{
int count;
public:
Counter()
{
count = 0;
}
Counter(int c)
{
count = c;
}
Counter operator++()
{
return Counter(++count);
}
Counter operator++(int)
{
return Counter(count++);
}
void put_count()
{
cout<
};
main()
{
ep
a
itn
Page 178
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Counter c1,c2,c3;
c1
...
put_count();
c2 = ++c1;
c3 = c2++;
c1
...
put_count();
c3
...
The one, for
prefix notation, is
Counter operator ++()
The one, for postfix notation, is
Counter operator ++(int)
The only difference is the int in the parentheses
...
It’s simply a signal to the compiler to create the postfix version of
the operator
...
Overloading binary operators
Binary operators are those that work on two operands
...
Overloading a binary operator is similar to overloading unary operator except that a
binary operator requires an additional parameter
...
It adds two objects of type ‘distance’
...
csitnepal
...
meter;
int cm = centimeter + d2
...
getDist();
d3 = d1 + d2; // Invokes operator+() function
d4 = d3
...
show();
d4
...
The argument on the left side the operator (d1 here) is the
object of which the operator is a member
...
Overloading Binary Operators Using Friend Function
ep
a
itn
Page 180
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Friend functions may be used in the place of member functions for overloading a binary
operator, the only difference being that a friend function requires two arguments to be
explicitly passed to it, while a member function requires only one
...
csitnepal
...
meter + d2
...
centimeter + d2
...
getDist();
d3 = d1 + d2;
d3
...
feet && inch == e
...
csitnepal
...
4);
equal e2(6,4
...
h>
#include
h>
#define SZ 20
class string
{
private:
char str[SZ];
public:
string()
{
strcpy(str," ");
}
string(char s[])
{
strcpy(str,s);
}
void getstring()
{
cout<<"\nEnter a string ";
cin>>str;
}
int operator ==(string ss)
{
return(strcmp(str,ss
...
csitnepal
...
getstring();
if(s3 == s1)
cout<<"\nYou typed Nepal";
else if(s3 == s2)
cout<<"\nYou typed Kathmandu";
else
cout<<"\nNot of both";
getch();
return 0;
}
//Overloading + operator to concatenate two strings
#include
h>
#include
str) < SZ)
{
strcpy(temp
...
str,ss
...
csitnepal
...
display();
s2
...
display();
cout<
return 0;
}
//Overloading < operator
class line
{
int feet;
float inch;
public:
line()
{}
line(int f,float i)
{
feet = f;
inch = i;
}
void display()
{
cout<
int operator<(line);
};
int line::operator<(line l)
{
float l1 = feet + inch/12;
float l2 = l
...
inch/12;
if(l1
else
return 0;
}
main()
{
ep
a
itn
Page 185
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
line l1(2,5
...
3);
if(l1
...
display();
getch();
return 0;
}
Multiple Overloading
We have seen several different uses of + operator: - to add distance and to concatenate
strings
...
It selects the correct function to carry out the addition
based on the type of operand
...
ep
a
itn
Page 186
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
h>
#include
meter;
int cm = centimeter + d2
...
str) < SZ)
{
strcpy(temp
...
str,ss
...
csitnepal
...
getDist();
d3 = d1 + d2;
d3
...
display();
s2
...
display();
getch();
return 0;
}
General rules for overloading operators
There are some restrictions and limitations to be kept in mind while overloading
operators
...
New operators can not be created
...
It is not recommended to change the basic meaning of an operator
...
Overloaded operators follow syntax rules of the original operators
...
Friend functions can not be used to overload certain operators like =, ( ), [ ] and >
...
But those overloaded by a friend
functions take one reference argument
...
Binary operators such as +, -, *, and / must explicitly return a value
...
itn
Page 188
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
Operator Overloading Restriction
Operator functions can not have default arguments
...
*, ?:, sizeof
...
Type Conversion (Data Conversion)
We use the assignment operator (=) to assign value of one variable to another
...
We have also noticed that = assigns the value of one
user defined object to another, provided that they are of the same type
...
The compiler
does not need any special instructions to use = for the assignment of user-defined objects
such as distance objects
...
But if the variables on different sides of the = are of different types, then the type of
variable on the right side of = needs to be converted to the type of left side variable
before the assignment takes place
...
Conversion Between Basic Types
Consider the statement,
intvar = floatvar;
where intvar is of type int and floatvar is of type float
...
There are many such
conversions: from float to double, char to float and so on
...
Such conversions are implicit conversion
...
For example,
ep
a
itn
Page 189
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
int total = 400;
float avg;
avg = float(total) / 5; // converts value of total to float before division takes place
...
Instead, we must write these routines
ourselves
...
These are sometimes
called conversion constructors
...
display();
getch();
}
From User-Defined to Basic Type
When class type data is converted into basic type data, it is called class to basic type
conversion
...
This type of
conversion takes place in casting operator
...
The syntax of casting operator function is
ep
a
itn
Page 190
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
operator typename()
{
………
...
}
This function converts a class type data to typename
...
The operator int() converts a class type object to
type int and so on
...
It must not specify a return type
...
class Stock
{
int items;
float price;
public:
Stock(int a,float p)
{
items = a;
price = p;
}
void putdata()
{
cout<<"Items: "<
operator float()
{
return (items*price);
}
};
main()
{
Stock s(45,2
...
putdata();
cout<<"Total float value = "<
return 0;
itn
Page 191
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
}
Another example
class DistConv
{
private:
int kilometers;
double meters;
static double kilometersPerMile;
public:
// This function converts a built-in type (i
...
miles) to the
// user-defined type (i
...
DistConv)
DistConv(double mile) // Constructor with one argument
{
double km = kilometersPerMile * mile ; // converts miles to
//kilometers
kilometers = int(km);
// converts float km to
//int and assigns to kilometer
meters = (km - kilometers) * 1000 ; // converts to meters
}
DistConv(int k, float m) // constructor with two arguments
{
kilometers = k ;
meters = m ;
}
// ********Conversion Function************
operator double()
// converts user-defined type i
...
// DistConv to a basic-type
{
// (double) i
...
meters
double K = meters/1000 ;
// Converts the meters to
// kilometers
K += double(kilometers) ;
// Adds the kilometers
return K / kilometersPerMile ; // Converts to miles
}
void display(void)
{
cout << kilometers << " kilometers and " << meters << " meters" ;
}
}; // End of the Class Definition
double DistConv::kilometersPerMile = 1
...
csitnepal
...
0 ;
// Uses the constructor with one argument
DistConv d2( 2, 25
...
255 kilometers = " << ml << " miles\n" ;
ml = d1 ;
// This form also uses conversion function
// and converts DistConv to miles
d1
...
255 kilometers = 1
...
72 meters = 5 miles*/
From One Class to Another Class Type
When a data of one class type is converted into data of another class type, it is called
conversion of one class to another class type
...
The class Y type data is
converted to the class X type data and converted value is assigned to the objx
...
This type of conversion is carried out by either constructor or
a conversion function
...
We know that the casting operator function
operator typename()
itn
Page 193
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Now consider a single-argument constructor function which serves as an instruction for
converting the argument’s type to the class type of which it is a member
...
The typename may be a
built-in type or user-defined type one
...
Therefore, when a class needs to be converted, a
casting operator function can be used (i
...
source class)
...
conversion
...
class Kilometers
{
private:
double kilometers;
public:
Kilometers(double kms)
{
kilometers = kms;
}
void display()
{
cout << kilometers << " kilometeres";
}
double getValue()
{
return kilometers;
}
};
itn
Page 194
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
class Miles
{
private:
double miles;
public:
Miles(double mls)
{
miles = mls;
}
void display()
{
cout << miles << " miles";
}
operator Kilometers()
{
return Kilometers(miles*1
...
getValue()/1
...
display();
cout << " = ";
k1
...
display();
cout << " = ";
m2
...
934 kilometeres
100 kilometeres = 62
...
csitnepal
...
csitnepal
...
getcode();
value = p
...
getprice();
}
};
main()
{
clrscr();
invent1 s1(100,5,140
...
putdata();
cout<<"Stock value"<<"\n";
cout<<"value = "<
d1
...
csitnepal
...
Write a program to overload += operator
...
Write a program to overload = operator (It is already overloaded in C++)
...
10
...
11
...
Overload + operator to add two objects of class Length
...
Also facilitate the operations like L4 = L1 + 5 and L5 = 5 + L4 where L1,
L2, L3, L4 and L5 are objects of class Length
...
12
...
Assume that the class distance contains two data members (feet
(integer type) and inch (floating point type)
...
33 feet and 1 feet
= 12 inches)
13
...
e
...
Let P1
and P2 be the objects of this class where P1 is initialized to (20, 30)
...
itn
Page 198
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
l
14
...
Virtual Function and Run Time Polymorphism
Pointers
Pointers have a reputation for being hard to understand
...
Addresses are numbers, just as they
are for houses on a street
...
If you have 1MB of
memory, the highest address is 1,048,575; for 16 MB of memory, it is 16,777,215
...
New and Delete Operator
Pointer provides the necessary support for C++ powerful dynamic memory allocation
system
...
For eg- int arr[100];
reserves memory for 100 integers
...
We must know at the time we write the program how big the
array will be and it is not always possible to predict what the size of the array will be
...
This capability is provided by the new operator
...
The syntax for the
new operator is
where
type of variable mentioned on the left hand side and the type mentioned on the right hand
side should match
...
csitnepal
...
For egchar *cptr;
cptr = new char[10];
allocates 10 bytes of memory and assigns the starting address to cptr
...
To ensure safe and efficient use of
memory, the new operator is matched by a corresponding delete operator that returns
memory to the operating system
...
However, this address is no longer valid, the memory it
points to may be changed to something entirely different but we do not use pointers
memory that has been deleted
...
For egdelete[] cptr;
//Example program that makes use of new and delete operator
#include
h>
class test
{
int x;
public:
void input()
{
cin>>x;
}
void display()
{
cout<
};
main()
{
test *t = new test;
t->input();
t->display();
delete t;
getch();
return 0;
}
ep
a
itn
Page 200
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
Polymorphism
In the programming sphere, polymorphism is broadly divided into two parts- the first part
being static polymorphism- exhibited by overloaded functions and the second being
dynamic polymorphism exhibited by late binding
...
Static polymorphism involves binding of functions on the basis of
number, type, and sequence of their arguments
...
This form of association is called early binding
...
The resolution is on the basis of number, type, and sequence of
arguments declared for each form of the function
...
void add(int, int);
void add(float, float);
Now, if the function add() is invoked, the parameters passed to it will determine which
version of the function will be executed
...
Dynamic Polymorphism
Dynamic polymorphism refers to an entity changing its form depending on the
circumstances
...
The term late binding refers to the resolution of the function to their
associated methods at run time instead of compile time
...
The compiler is unable to bind a call to a method since resolution depends
on the context of the call
...
Virtual Functions
Virtual means existing in appearance but not in reality
...
A function is made virtual by placing the keyword virtual
before its normal declaration
...
ep
a
itn
Page 201
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
#include
h>
class Base
{
public:
void show()
{
cout<<"Base\n";
}
};
class Derv1 : public Base
{
public:
void show()
{
cout<<"Derv1\n";
}
};
class Derv2 : public Base
{
public:
void show()
{
cout<<"Derv2\n";
}
};
int main()
{
Derv1 d1;
Derv2 d2;
Base *ptr; // pointer to base class
ptr = &d1;
ptr->show();
ptr = &d2;
ptr->show();
getch();
return 0;
}
itn
Page 202
cs
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
Virtual Member Functions Accessed with Pointers
Let’s make a single change in the above program
...
#include
h>
l
Output of the program
Base
Base
The function in the base class is always executed
...
class Base
{
public:
virtual void show()
{
cout<<"Base\n";
}
};
class Derv1 : public Base
{
public:
void show()
{
cout<<"Derv1\n";
}
};
class Derv2 : public Base
{
public:
void show()
{
cout<<"Derv2\n";
}
};
int main()
{
Derv1 d1;
Derv2 d2;
Base *ptr;
ptr = &d1;
ptr->show();
ptr = &d2;
ptr->show();
getch();
return 0;
}
Output of the program
Derv1
Derv2
Now, as you can see, the member functions of the derived classes, not the base class, are
executed
...
So the same function call,
ep
a
itn
Page 203
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
ptr->show();
executes different functions, depending on the contents of ptr
...
Here,
the compiler does not know what class the contents of ptr may contain
...
Which version of show()
does the compiler call? In fact the compiler does not know what to do, so it arranges for
the decision to be deferred until the program is running
...
Abstract Classes and Pure Virtual Functions
An abstract class is one that is not used to create objects
...
A class is made an
abstract by placing at least one pure virtual function in the class
...
i
...
a pure virtual function can be
declared by equating it to zero
...
The =0 syntax is simply how we will tell the compiler that a function will be
pure
...
If a class does not
override the pure virtual function, then it becomes an abstract class itself, and we can not
instantiate objects from it
...
We can not create objects of the abstract class
...
This allows an abstract class to be used as a base class, pointers to which
can be used to select the proper virtual function
...
csitnepal
...
h>
#include
csitnepal
...
h>
#include
csitnepal
...
5) ? 1 : 0;
}
};
class professor : public person
{
private:
int numpubs;
public:
void getData()
{
person :: getName();
cout<<"\nEnter number of publications";
cin>>numpubs;
}
int isOutstanding()
{
return (numpubs > 100)?1 : 0;
}
};
main()
{
person *persptr[100];
int n = 0;
char choice;
do
{
cout<<"\nEnter student or professor(s/p)";
cin>>choice;
if(choice == 's')
persptr[n] = new student;
else
persptr[n] = new professor;
persptr[n++]->getData();
cout<<"\nAnother record? ";
cin>>choice;
}while(choice == 'y');
for(int j = 0;j < n; j++)
{
persptr[j]->putName();
if(persptr[j]->isOutstanding())
cout<<"\nThis person is outstanding";
}
getch();
return 0;
}
Friend class
The member functions of a class can all be made friends at the same time when we make
the entire class a friend
...
#include
h>
class alpha
{
int data;
public:
alpha()
{
data = 10;
}
friend class beta; // beta is friend class
};
class beta
{
public:
void func1(alpha a)
{
cout< ...
data;
}
};
main()
{
ep
a
itn
Page 207
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
alpha a;
beta b;
b
...
func2(a);
getch();
return 0;
}
In class alpha the entire class beta is defined as a friend
...
The this Pointer
The member functions of every object have access to a sort of magic pointer named this,
which points to the object itself
...
h>
#include
TestThisPointer();
m2
...
The this pointer can be treated like any
other pointer to an object, and can thus be used to access the data in the object it points
to
...
csitnepal
...
test();
getch();
return 0;
}
This program simply prints the value 10
...
csitnepal
...
class alpha
{
int data;
public:
alpha()
{}
alpha(int x)
{
data = x;
}
void display()
{
cout<}
alpha& operator = (alpha &a)
{
data = a
...
display();
l
This is exactly the same as referring to x directly
...
display();
getch();
return 0;
}
ep
a
itn
Page 210
cs
Source: www
...
com (By:Tej Bahadur Shahi)
l
//using this pointer for returning value from member function
class Distance
{
int meter;
int centimeter;
public:
Distance()
{
meter = 0;
centimeter = 0;
}
Distance (int m, int cm)
{
meter = m;
centimeter = cm;
}
void getDist()
{
cout<<"Enter meter";
cin>>meter;
cout<<"Enter centimeter";
cin>>centimeter;
}
void show()
{
cout<
Distance compare(Distance);
};
Distance Distance :: compare(Distance d2)
{
float dist1 = meter + (float)centimeter/100;
float dist2 = d2
...
centimeter/100;
if(dist1 < dist2)
return *this;
else
return d2;
}
main()
{
Distance d1(4,50);
Distance d2,d3,d4;
d2
...
compare(d2);
cout<<"Small lenght is: ";
d4
...
csitnepal
...
It supports the generic data types
and generic programming
...
Templates are a feature of the C++ programming language that allows functions and
classes to operate with generic types
...
A template is a way to specify generic code, with a placeholder for the type
...
Templates offer several advantages:
Templates are easier to write
...
Templates can be easier to understand, since they can provide a straightforward
way of abstracting type information
...
Because the types that templates act upon are known at
compile time, the compiler can perform type checking before errors occur
...
However, there are many differences between a macro like this:
#define min(i, j) (((i) < (j)) ? (i) : (j))
and a template:
template
Here are some problems with the macro:
Source: www
...
com (By:Tej Bahadur Shahi)
Page 212
l
ep
a
itn
There is no way for the compiler to verify that the macro parameters are of
compatible types
...
The i and j parameters are evaluated twice
...
Because macros are expanded by the preprocessor, compiler error messages will
refer to the expanded macro, rather than the macro definition itself
...
cs
Templates in c++ comes in two variations
a) function templates
b) class templates
Class template
The relationship between a class template and an individual class is like the relationship
between a class and an individual object
...
The general form of a class template is
Template
Class class_name
{
//class member with type T whenever appropriate
};
Example
#include
x = v1
...
y = v1
...
csitnepal
...
9,6
...
0,-2
...
Compiler generates classes for only the used types
...
Templates reduce the effort on coding for different data types to a single set of
code
...
Function template
To perform identical operations for each type of data compactly and conveniently, we use
function templates
...
Based on the
argument types provided in calls to the function, the compiler automatically instantiates
separate object code functions to handle each type of call appropriately
...
When the
compiler sees an instantiation of the function template, for example: the call max(10, 15)
in function main, the compiler generates a function max(int, int)
...
Page 214
itn
Source: www
...
com (By:Tej Bahadur Shahi)
ep
a
//function template
cs
template
l
#include
using namespace std ;
//max returns the maximum of the two elements
T max(T a, T b)
{
return a > b ? a : b ;
}
int main()
{
cout << "max(10, 15) = " << max(10, 15) << endl ;
cout << "max('k', 's') = " << max('k', 's') << endl ;
cout << "max(10
...
2) = " << max(10
...
2) << endl ;
return 0;
}
Output:
max(10, 15) = 15
max('k', 's') = s
max(10
...
2) = 15
...
The keyword class, within the angle brackets, might just as well be called type
...
The variable following the keyword class (T in
this example) is called the template argument
...
csitnepal
Title: C++
Description: A simple and easy note is here for u...I can bet u gonna pass any exam with this note...so guys what are you looking for??Download it and enjoy
Description: A simple and easy note is here for u...I can bet u gonna pass any exam with this note...so guys what are you looking for??Download it and enjoy