Professional Documents
Culture Documents
Introduction of C++:
C++ is one of the world's most popular programming languages.
C++ is an extension to the C language.
C++ also called as “C with Classes “.super-set of C language.
C++ is a Objected Oriented Programming language and facilitates design, resuse and
maintenance for complex software.
C++ Features
The C++ (also read as C plus plus) is a general-purpose object oriented programming language. C++
is an enhanced version of the C language introduced with many new features
Simple :-
C++ comes with easy to learn simple English language like syntax, which makes it very easy to
understand and develop C++ Programs.
Statically Typed :-
This allows compiler to catch the bugs before executing the program.
Multi Paradigm :-
C++ is a multi-paradigm object oriented programming language that supports procedural,
object-oriented (OOPs), and generic programming whereas C is a procedural programming
language.
Object Oriented :-
C++ is a general-purpose, multi-paradigm object oriented programming language that
supports procedural, object-oriented (OOPs), and generic programming whereas C is a
procedural programming language. It compliance with four of the major OOPs principles
Inheritance, Polymorphism, Encapsulation and Abstraction.
Standard Template Library(STL) :-
C++ comes with rich inbuilt function library through Standard Template Library (STL).
Pointers :-
C++ supports the use of pointers which are often not available in several programming
languages.
Portable :-
C++ is Portable language, which allows you writing a program irrespective of operating
system as well as Hardware. Programs written in C++ can be executed in many machines with
little bit or no change.
C++ is a highly portable language that supports multi-device, multi-platform application
development.
Reusable :-
C++ comes with an increased level of code re-usability due to the object oriented programming
model and libraries.
Exception handling :- C++ supports exception handling which was not possible in C.
Case Sensitive :- C++ is a case sensitive programming language. In C++ programming “abc”
and “ABC” both are different.
Compiled :- C++ is compiled language, which means C++ source code need to be first compiled
into low-level code and then it can be executed, unlike interpreted programming languages where
compilation is not needed.
History of C++:
C++ was developed by Bjarne Stroustrup in 1979 at Bell Labs.
It was the first language to support the OOPS concepts.
First it called as “C with Classes “.
In 1983, the name was changed to C++ .Here ++ refers to adding new features (inheritance,
pholymarphizam, classes, objects) to the C languages.
Application of C++ :
1. Operating Systems
Microsoft Windows or Mac OSX or Linux - all of them are programmed in C++. C/C++ is
the backbone of all the well-known operating systems
2. Browsers
Web browsers ( Google chrome,Mozilla Firefox.IE) are programmed in C++.
Faster execution to make sure that users don’t have to wait for the content to come
up on the screen.
3. Libraries
Many high-level libraries use C++ as the core programming language.
One of the most widely used Machine Learning libraries uses C++ as the
backend programming language. Such libraries required high-performance
computations. As a result, performance becomes critical.
C++ comes to the rescue in such libraries.
4. Graphics
All graphics applications require fast rendering
. Software that employ computer vision, digital image processing, high-end
graphical processing - they all use C++ as the backend programming language.
Even the popular games that are heavy on graphics use C++ as the primary
programming language.
The speed that C++ offers in such situations helps the developers in expanding the
target audience because an optimized application can run even on low-end
devices that do not have high computation power available.
5. Banking Applications
One of the most popularly used core-banking system - Infosys Finacle uses C++ as one
of the backend programming languages.
Banking applications process millions of transactions on a daily basis and require high
concurrency.
C++ automatically becomes the preferred choice in such applications owing to its
speed and multithreading support that is made available through various Standard
Template Libraries that come as a part of the C++ programming kit.
6. Cloud/Distributed Systems
Large organizations that develop cloud storage systems and other distributed systems
also use C++ because it connects very well with the hardware and is compatible with a
lot of machines.
Cloud storage systems use scalable file-systems that work close to the hardware.
C++ becomes a preferred choice in such situations because it is close to the hardware
and also the multithreading libraries in C++ provide high concurrency and load
tolerance which is very much needed in such scenarios.
7.Databases
Postgres and MySQL - two of the most widely used databases are written in C++ and C, the
precursor to C++.
These databases are used in almost all of the well-known applications that we all use in our day
to day life - Quora, YouTube, etc.
8. Embedded Systems
Various embedded systems like medical machines, smart watches, etc. use C++ as the primary
programming language because of the fact that C++ is closer to the hardware level as compared to other
high-level programming languages.
9. Telephone Switches
Because of the fact that it is one of the fastest programming languages, C++ is widely used in
programming telephone switches, routers, and space probes.
10. Compilers
The compilers of various programming languages use C and C++ as the backend programming language.
cin>>name;
cout<<”enter employee salary”<<endl;
cin>>salary;
}
void putdata()
{
cout<<” employee no”<< eno <<endl;
cout<<” employee name”<< name <<endl;
cout<<”enter employee salary”<< salary <<endl;
}
};
void main ()
{
clrscr();
Employee e;
e.getdata();
e.putdata();
getch();
}
Output :
enter employee no 101
enter employee name RAJU
enter employee salary 20,000
employee no 101
employee name RAJU
employee salary 20,000
C++ TOKENS
A token is the smallest element of a program that is
meaningful to the compiler.
Tokens can be classified as follows:
Keywords
Identifiers
Constants
Strings
Special Symbols
Operators
1.Keywords:
Keywords are pre-defined or reserved words in a programming language. Each keyword is
meant to perform a specific function in a program.
C language supports 32 keywords which are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
2.Identifiers:
Identifiers are used as the general terminology for the naming of variables, functions and
arrays.
These are user-defined names consisting of an arbitrarily long sequence of letters and digits
with either a letter or the underscore(_) as a first character.
Identifier names must differ in spelling and case from any keywords.
You cannot use keywords as identifiers;
they are reserved for special use. Once declared, you can use the identifier in later program statements
to refer to the associated value.
A special kind of identifier, called a statement label, can be used in goto statements.
There are certain rules that should be followed while naming c identifiers:
They must begin with a letter or underscore(_).
They must consist of only letters, digits, or underscore. No other special character is allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only the first 31 characters are significant.
main: method name.
a: variable name.
3.Constants: Constants are also like normal variables. But, the only difference is, their values can
not be modified by the program once they are defined. Constants refer to fixed values. They are also
called literals.
Constants may belong to any of the data type
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of Constants:
Integer constants – Example: 0, 1, 1218, 12482
Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184
Octal & Hexadecimal constants – Example: octal: (013 ) 8 = (11)10, Hexadecimal: (013)16 =
(19)10
Character constants -Example: ‘a’, ‘A’, ‘z’
String constants -Example: “GeeksforGeeks”
4.Strings: Strings are nothing but an array of characters ended with a null character (‘\0’). This null
character indicates the end of the string. Strings are always enclosed in double-quotes. Whereas, a
character is enclosed in single quotes in C and C++.Declarations for String:
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;
when we declare char as “string[20]”, 20 bytes of memory space is allocated for holding the
string value.
When we declare char as “string[]”, memory space will be allocated as per the requirement
during the execution of the program.
5.Special Symbols: The following special symbols are used in C having some special meaning
and thus, cannot be used for some other purpose.[] () {}, ; * = #
Brackets[]: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
Comma (, ): It is used to separate more than one statements like for separating parameters in
function calls.
Colon(:): It is an operator that essentially invokes something called an initialization list.
Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity.
That’s why each individual statement must be ended with a semicolon.
Asterisk (*): It is used to create a pointer variable.
Assignment operator(=): It is used to assign values.
Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
6.Operators: Operators are symbols that trigger an action when applied to C variables and
other objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be classified
as follows:
Unary Operators: Those operators that require only a single operand to act upon are known as
unary operators.For Example increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operator
OOPs Concepts
Object-Oriented Programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Data Abstraction & Encapsulation
6. Message communication
7. Dynamic binding
Data Abstraction: Hiding the implementation details of a particular object is known as Data abstraction
Data Encapsulation: Combining all the functions together is known as Data Encapsulation.
- The wrapping of data and methods into a single unit is called encapsulation which is one of the
important features of class. The data is not accessible to the outside world and only those methods which
are wrapped in the class can access it which is known as data hiding.
Inheritance: It is the process by which the objects of one class acquire the properties of objects of
another class.
- Extending the parent class properties to child class is the concept of Inheritance.
-It provides the idea of reusability which means that we can additional features to an existing class
without modifying it which is possible by deriving a new class from the existing one where the new class
will have the combined features of both the classes.
Dynamic binding
Means that the code associated with given procedure call is not known until the time of the call at
runtime. It is associated with polymorphism and inheritance.
Message Communication
Objects communicate with each other by sending and receiving information as people.
It involves specifying the name of the object, method name and information to be sent.
example:
Employee. salary (ename);
Programming approaches
1. Top to down approach -C
2. Bottom to top approach - C++
Output Operator
The statement
cout<<”welcome to C++ programming”;
causes the string in quotation marks to be displayed on the screen. The identifier cout (pronounced as ‘C
out’) is a predefined object that represents the standard output stream(ostream)in C++.
The operator << is called the insertion or put to operator which inserts or sends the contents of the
variable on its right to the object on its left.
Screen
^
|
Cout------------------ <<---------------------------------C++
Object insertion operator variable
Return Statement
main() returns integer type to operating system. Therefore every main() in C++ should end with
return(0) statement otherwise a warning may occur.(function should return a value)
Input operator
int number1;
cin>>number1;
Is an input statement & causes the program to wait for the user to type in a number which is
placed in the variable number1. The identifier cin (pronounced as “C in”) is a predefined object in C++
that corresponds to the standard input stream which is keyboard.
The operator >> is known as extraction or get from operator which extracts or takes the value
from the keyboard and assigns it to the variable on its right.
Cin--------------->>---------------------------------------12.5
Object extraction operator variable
^
|
Keyboard
Cascading of I/O Operators
The multiple use of << and >> in one statement is known as cascading.
Example:
cout<<”sum = “<<sum;
cin>>a>>b;
o/p:
sum=10
Basic Syntax:
Case Sensitivity–C++ is case sensitive, which means identifier Hello and hello would have different
meaning in C++.
ASCII (American standard code for information interchange) Characters
A to Z - 65 to 90 (+- 32)
a to z - 97 to 122
0 to 9 - 48 to 56
Identifiers &keywords
All C++ components require names. Names used for variables, functions etc are called identifiers.
In C++, there are several points to remember about identifiers. They are as follows
Ex: stud_name1
3. A key word cannot be used as an identifier.
4. Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
The following list shows the reserved words in C++. These reserved words may not be used as constant
or variable or any other identifier names.
Variable : It is a data item that stores data value that changes(varies) during program execution.
Syntax:
datatype variable(s);
ex:
int a;
int b,c;
or
int a,b,c;
char x;
float y;
double z;
constants : refers to fixed value whose value does not change during program execution.
- Constants are declared using the keyword const
Ex:
Const float pi=3.14;
2) enum{var1,var2,….};
Enum stands for enumeration
Ex:
enum{a,b,c};
declares a,b and c as set of integer constants with the values assigned 0,1,2;
which is equivalent to
const int a=0,b=1,c=2;
enum{a,b,c=10};
a=0,b=1,c=10
enum{a,b=5,c};
a=0,b=5,c=6
Reference variables
It provides an alias or alternate name for previously defined variable.
Syntax:
datatype & referencename=variable name;
Example:
float total=200;
float&sum=total; //reference variable
cout<<total;o/p 200
cout<<sum;o/p 200
Operators
It is symbol to perform an operation.
- Arithmetic operators +-*/%
- Relational operators <>>= <= <> ==
- Logical “ && || !
- Assignment “ =
- Bit wise “
- Increment & decrement “ ++ --
- Special operators , & *
- Conditional operators ? :
CHANDRA MOULI (DEPT OF CS in KU) Page 12
9640235390
PROGRAMMING IN C++
- size of “
C++ Operators
<< insertion operator
>> extraction operator
:: scope resolution operator
::* pointer-to member declarator
->* pointer to member operator
.* pointer to member operator
Delete memory release operator - memory management operators
new memoryallocation operator
endl line feed operator - manipulators
setw field width operator
:: scope resolution operator
It allows access to global version of a variable and also used to specify to which class that
function belongs to.
//scope.cpp
//program to demonstrate scope resolution operator ::
#include<iostream.h>
#include<conio.h>
sequential statements – are the statements which are executed in a sequential manner. These are by
default.
Selection statements – are those statements which are executed basing on certain condition (selection).
Ex: decision making statements(if construct,switch construct)
Iterative statements – are those statements which are executed repeated number of times as long as
condition is true or until condition becomes false.
Ex:do loop, for loop, while loop
Functions
Advantages
- Readability
- Reusability
Types of functions
1. Built in / predefined functions/library functions – are those functions which are ready made
available
2. User defined functions (UDF’s) – are those functions which are defined by the user as per his
requirement.
Types of arguments
1. Actual arguments – are those arguments which are passed from main to sub program.
2. Formal arguments – are those arguments which are declared in sub program to receive the formal
arguments sent from main program matching the order, number and type of arguments.
Function prototyping
It describes the function interface to the compiler by giving details like number & type of
arguments and type of return values.
CHANDRA MOULI (DEPT OF CS in KU) Page 14
9640235390
PROGRAMMING IN C++
Syntax:
Type functionname (argument-list);
Note: argument list contains the type and names of arguments that must be passed to the function.
Void func(int,int); //function prototyping
Main()
{
Int a,b;
Func(a,b); // aa
}
Invoking/Calling a function
A function can be called in3 ways
. Call/Pass by value
. Call by address (pointers)
. Call by reference
Call by value
When a function is called by value, copy of values passed by actual arguments is received by
formal arguments on one to one basis matching the order, data type & size.
Any changes made to the formal argument values that do not reflect the actual argument values
since their address differ.
Ex: callbyval.cpp
//demonstration of call by value
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
//function prototyping
void func(int);
//main or calling program
main()
{
int a;
clrscr();
cout<<"enter value for a"<<endl;
cin>>a;
cout<<"value of a before function call is : "<<a<<endl;
//calling function with argument & no return value
func(a);
cout<<"value of a after function call is : "<<a<<endl;
return(0);
}
//function prototyping
void func(int*);
//main or calling program
main()
{
int a;
clrscr();
cout<<"enter value for a"<<endl;
cin>>a;
cout<<"value of a before function call is : "<<a<<endl;
//calling function with argument & no return value
//call by address
func(&a);
cout<<"value of a after function call is : "<<a<<endl;
return(0);
}
{
(*x)++;
cout<<"value of x is :"<<*x<<endl;
}
Call by Reference
//callbyrf.cpp
//demonstration of call by reference
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
//function prototyping
void func(int&);
//main or calling program
main()
{
int a;
clrscr();
cout<<"enter value for a"<<endl;
cin>>a;
cout<<"value of a before function call is : "<<a<<endl;
//calling function with argument & no return value
//call by reference
func(a);
cout<<"value of a after function call is : "<<a<<endl;
return(0);
}
The above problem can be solved in C++ using Functions with default arguments.
C++ allows to call a function without specifying all its arguments. In such cases, the function
assigns a default value to the parameter which does not have matching argument in the function call.
Default arguments are specified when the function is declared. The compiler looks at the
prototype to see how many arguments a function uses and alters the program for possible default values.
Note:
1. A default argument is checked for type at the time of declaration and evaluated at the time of call.
2. Only the trailing arguments can have default values i.e. from right to left.
3. Default value cannot be provided to a particular argument in the middle of an argument list.
//defaarg.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//function with default arguments
//function prototypedeclaration
void func (int p, int q, int r=35);
void main()
{
int a, b;
clrscr ();
cout<<"enter value for a and b"<<endl;
cin>>a>>b ;
func(a,b); // one argument missing
}
//sub program
void func(int x,int y,int z)
{
int d;
cout<<"value of x is :"<<x<<endl;
cout<<"value of y is :"<<y<<endl;
cout<<"value of z is :"<<z<
Function Overloading
It is the usage of same function name to create functions that perform a variety of different tasks.
This is known as function polymorphism/function overloading in OOPS.
-The function would perform different operations depending on the argument list in the function call and
the correct function to be invoked is determined by checking the number & type of the arguments but
not on the function type.
Example 1:
//demonstration of function overloading
//addition of 2 character, 2 integers & 2 floating values
//funcover.cpp
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
//function prototyping
char add(char,char);
int add(int,int);
float add(float,float);
//calling a function
//call by value
p=add(a,b);
q=add(c,d);
r=add(e,f);
cout<<"addition of"<<a<<" + "<<b<<" is :"<<p<<endl;
cout<<"addition of"<<c<<" + "<<d<<" is :"<<q<<endl;
cout<<"addition of"<<e<<" + "<<f<<" is :"<<r<<endl;
return(0);
}
//integer addition
int add(int m,int n)
{
return(m+n);
}
//floating addition
float add(float r,float s)
{
return(r+s);
}
Example 2:
//funover1.cpp
//function overloading
//drawing lines in different designs
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
//function prototyping
void line(void);
void line(char);
void line(int);
void line(char,int);
//main or calling program
main()
{
clrscr();
//calling a function
//call by value
line();
line('*');
line(70);
line('=',80);
return(0);
}
void line(char x)
{
for(int i=1;i<=60;i++)
{
cout<<x;
}
cout<<endl;
}
void line(int m)
{
for(int i=1;i<=m;i++)
{
cout<<"+";
}
cout<<endl;
}
A class is collection of objects of similar type which is an extension of the idea of structure of C.
Class has 2 parts namely
- Class declaration – describes the type & scope of its members
- Class function definitions – describes how the class functions are implemented.
Declaration of class
class <classname>
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
private
Members that have been declared as private can be accessed only form within the class. If nothing is
specified, by default it is private.
public
public members can be accessed from outside the class too.
Note:
Variables declared inside the class are known as data members and functions are known as member
functions or methods
Objects
Syntax:
Classname object(s);
Example:
class fruit
{
int a;
======
};
void main()
{
fruit mango,banana; //class type variables ie objects
}
mango.a=10;
mango.getdata();
//insclass.cpp
//inside class definition
//defining member function inside the class definition
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void putdata(void)
{
cout<<"roll number="<<rno<<endl;
cout<<"name ="<<name<<endl;
}
}; //end of class
void main()
{
student s; //object
clrscr();
//invoking member functions of object
s.getdata();
s.putdata();
}
Syntax:
return-type classname : : functionname(argument declaration)
{
function body;
}
NOTE:
- The membership label class-name:: tells the compiler that the function function-name belongs to
the class class-name. That is, the scope of the function is restricted to the class name specified in the
header line.
- The symbol:: is called scope resolution operator.
//outclass.cpp
//defining member function outside the class
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class student
{
//private data members
int rno;
char name[16];
public:
void getdata(void); //prototype declarations
void putdata(void);
};
void main()
{
student s; //object creation
clrscr();
//invoking member functions on object
s.getdata();
s.putdata();
}
//nestfunc.cpp
//nesting of member functions
//finding largest of 2 numbers
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class big
{
//private data members
int a,b;
public:
void getdata(void); //prototype declarations
void putdata(void);
int biggest(void);
};
void main()
{
big b; //object creation
clrscr();
//invoking member functions on object
b.getdata();
b.putdata();
}
Int a,x;
Char b,y;
Float c,z;
X=Fun1(a);
Y=Fun2(b);
Z=Fun3(c);
//addtime.cpp
//addition of 2 times without any return value
//function with object as argument without return value
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class time
{
//private data members
int hours,minutes;
public:
//getting time
void gettime(int h,int m)
{
hours=h;
minutes=m;
}
//displaying time
void puttime(void)
{
cout<<" hours = "<<hours<<" and minutes ="<<minutes<<endl;
}
//addition of 2 times
void sum(time tt1,time tt2)
{
minutes=tt1.minutes+tt2.minutes;
hours=minutes/60;
minutes=minutes%60;
hours=hours+tt1.hours+tt2.hours;
}
};
void main()
{
time t1,t2,t3;
clrscr();
t1.gettime(3,45); //get time1
t2.gettime(4,55); //get time2
//addition of 2 times
t3.sum(t1,t2); //calling sum function with object as function argument
//t3=t1+t2;
cout<<"time 1 ="<<endl;
t1.puttime();
cout<<"time t2="<<endl;
t2.puttime();
cout<<"time 3="<<endl;
t3.puttime();
}
//addtimer.cpp
//addition of 2 times
//function with object as argument and with return value
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class time
{
//private data members
int hours,minutes;
public:
//getting time
void gettime(int h,int m)
{
hours=h;
minutes=m;
}
//displaying time
void puttime(void)
{
cout<<" hours = "<<hours<<" and minutes ="<<minutes<<endl;
}
//addition of 2 times
time sum(time tt2)
{
time t;
t.minutes=minutes+tt2.minutes;
t.hours=t.minutes/60;
t.minutes=t.minutes%60;
t.hours=t.hours+hours+tt2.hours;
return t;
}
};
void main()
{
time t1,t2,t3;
clrscr();
t1.gettime(3,45); //get time1 //explicit function call
t2.gettime(4,55); //get time2
//addition of 2 times
t3=sum(t2); //calling sum function with object as function argument
//t3=t1+t2;
cout<<"time t1 ="<<endl;
t1.puttime(); //explicit function call
cout<<"time t2="<<endl;
t2.puttime();
cout<<"time 3="<<endl;
t3.puttime();
}
Constructor
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.
- It is so called because it constructs the values of the data members of the class.
-
Syntax:
class <classname>
{
private:
Public:
//constructor function definition
classname()
{
Function body;
}
};
Characteristics of Constructor
1. Function name should have same name as that of class name
2. Should be declared in the public section
3. Invoked automatically whenever object is created
4. They do not have return types
5. They cannot be inherited thru a derived class but can call the base class
Constructor
6. They can have default arguments
Types of constructors
1. Default constructor
2. Parameterized constructor
3. Copy constructor
Default constructor
A constructor that accepts no parameters is called default constructor.
void main()
{
defcons def; //default constructor
clrscr();
def.display(); //explicitly invoking a function on object
}
Parameterised constructor
Constructor that takes arguments is called parameterized constructor.
void main()
{
paracons para(5,10); //parameterised constructor
clrscr();
para.display(); //explicitly invoking a function on object
}
//dfcontme.cpp
//addition of 2 times
//function with object as argument and with return value
//class with default ¶meterized constructor
// Working with multiple constructors
//constructor overloading
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//time sum(time);
class time
{
//private data members
int hours,minutes;
public:
//default constructor definition
time()
{
hours=0;
minutes=0;
}
//parameterised constructor definition
time(int hrs,int mins)
{
hours=hrs;
minutes=mins;
}
//displaying time
void puttime(void)
{
cout<<" hours = "<<hours<<" and minutes ="<<minutes<<endl;
}
//addition of 2 times
time sum(time tt2)
{
time t;
t.minutes=minutes+tt2.minutes;
t.hours=t.minutes/60;
t.minutes=t.minutes%60;
t.hours=t.hours+hours+tt2.hours;
return t;
}
};
void main()
{
time t1(3,45),t2(4,55); parameterized constructor
time t3; //default constructor
clrscr();
//addition of 2 times
//calling sum function with object as function argument and with return value
t3=t1.sum(t2);
//t3=t1+t2;
cout<<"time 1 ="<<endl;
t1.puttime();
cout<<"time t2="<<endl;
t2.puttime();
cout<<"time 3="<<endl;
t3.puttime();
}
Copy Constructor
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class copy
{
//private data members
int id;
public:
//default constructor definition
copy()
{
};
//parameterised constructor definition
copy(int a)
{
id=a;
}
//copy constructor
copy(copy &x)
{
id=x.id; //copying the value
void display(void)
{
cout<<"id value = "<<id<<endl;
}
};
void main()
{
copy A(11); //object A is created and initialized
copy B(A); // copy constructor called
copy C=A; // copy constructor called again
copy D;// object D is created but not initialized
D=A; // copy constructor called again
clrscr();
cout<<"value of id of A="<<endl;
A.display();
cout<<"value of id of B="<<endl;
B.display();
cout<<"value of id of C="<<endl;
C.display();
cout<<"value of id of D="<<endl;
D.display();
}
Destructors
As the name indicates, it is used to destroy the objects that have been created by a constructor.
- Like a constructor, destructor is a member function whose name is same as the class name but it
is preceded by a tilde symbol(~)
Characteristics
. Declared in public section
. Has same name as that of class name but preceded by tilde symbol ( ~ )
. Does not return any value
//defcons.cpp
///class with default constructor & destructor
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class destruct //classname
{
//private data members
int a,b,c;
public:
//default constructor definition
destruct(void)
{
a=5; //giving initial values to data members a and b
b=10;
}
//destructor function definition
~destruct(void)
{
clrscr();
cout<<" value of a ="<<a<<endl;
cout<<" value of b ="<<b<<endl;
c=a+b;
cout<<"sum is "<<c<<endl;
}
};
void main()
{
destruct des; //default constructor
}
Advantages of inheritance
-Reusability
- Avoiding duplication of code
- Time
- Speed
Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
A derived class is defined by specifying its relationship with the class in addition to its own details.
};
- The : colon indicates that the derivedclassname is derived from the baseclassname.
- The visibility mode is optional. If present, it can be either private or public.
- The default visibility mode is private which specifies that whether the features of the base class
are privately derived or publicly derived.
Private Derivation
When base class is privately inherited by a derived class, “public members” of the base class
become “private members” of the derived class and therefore the public members of the base class only
are accessed by the member functions of the derived class. They are inaccessible to the objects of the
derivedclass.
Public Derivation
When the base class is publicly inherited, “public members” of the base class becomes “public
members” of the derived class and therefore they are accessible to the objects of the members of a
derived class.
Single Inheritance
Diagram
//sngleinh.cpp
//single inheritance
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class base
{
//private data members
int a; //not inheritable
public:
int b; //ready for inheritance
void getab(void);
int geta(void);
CHANDRA MOULI (DEPT OF CS in KU) Page 34
9640235390
PROGRAMMING IN C++
void show(void);
};
//derived class
void main()
{
derived d; // derived class object
clrscr();
d.getab();
d.mul();
d.show();
d.display();
Protected C++ provide third visibility modifier called protected. A member declared as protected is
accessible by the member functions within a class and any class immediately derived from it. It cannot be
accessed by the functions outside these two classes.
Example:
class sample
{
private: //optional
==== //visible to member functions within its class
---------
protected:
--------- //visible to member functions of its own and also derived class
---------
public:
--------- // visible to all functions in the program
----------
};
Multilevel Inheritance
Mechanism of deriving a Class from another derived class is known as Multilevel Inheritance.
Diagram
//mulvlinh.cpp
//implementation of Multi level inheritance
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//base class
class student
{
//private data members
int rno;
char name[16];
public:
void getstuddetails(void)
{
cout<<"enter roll number and name"<<endl;
cin>>rno>>name;
}
void putstuddetails(void)
{
cout<<" roll number="<<rno<<endl;
cout<<"name ="<<name<<endl;
}
};
public:
void getmarks(void)
{
cout<<"enter any 3 subject marks"<<endl;
cin>>sub1>>sub2>>sub3;
}
void putmarks(void)
{
cout<<"sub1 marks ="<<sub1<<endl;
cout<<"sub2 marks ="<<sub2<<endl;
cout<<"sub3 marks ="<<sub3<<endl;
}
};
//derived class
class result : public marks
{
private:
int total;
float avg;
public:
void caluculate(void)
{
total=sub1+sub2+sub3;
avg=total/3;
}
//nesting of member functions
void displayresult(void)
{
putstuddetails(); //nesting of functions
putmarks();
cout<<"total marks ="<<total<<endl;
cout<<"average marks="<<avg<<endl;
}
};
void main()
{
result r; //derived class object
clrscr();
r.getstuddetails();
r.getmarks();
r.caluculate();
// r.putstuddetails();
// r.putmarks();
r.displayresult();
}
Multiple Inheritance
Diagram
Syntax:
Class D: visibility B-1, visibility B-2,
{
====
====
Body of D
};
//multiinh.cpp
//implementation of multiple inheritance
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//base class1
class base1
{
protected:
int a;
public:
void geta(int x)
{
a=x;
}
};
//base class2
class base2
{
protected:
int b;
public:
void getb(int y)
{
b=y;
}
};
//derived class
class derived : public base1,public base2
{
public:
void display(void)
{
cout<<"value of a="<<a<<endl;
cout<<"value of b ="<<b<<endl;
cout<<"a + b ="<<a+b<<endl;
}
};
void main()
{
derived d; //derived class object
clrscr();
d.geta(4);
d.getb(5);
d.display();
}
Hierarchical Inheritance
In this form, the properties of one class are inherited by more than one class.
Diagram
//hirarcin.cpp
//implementation of Hierarchical Inheritance
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//base class
class student
{
int rno;
char *name; //char pointer
public:
void getstuddetails(int r,char *n)
{
rno=r;
name=n;
}
void putstuddetails(void)
{
cout<<"roll number="<<rno<<endl;
cout<<"name ="<<name<<endl;
}
};
//derived class1
class internal1 : public student
{
private:
int sub1,sub2,sub3;
public:
void getinternal1marks(int s1,int s2,int s3)
{
sub1=s1;
sub2=s2;
sub3=s3;
}
void putinternal1marks(void)
{
cout<<"subject1 marks="<<sub1<<endl;
cout<<"subject2 marks="<<sub2<<endl;
cout<<"subject2 marks="<<sub3<<endl;
}
};
//derived class2
class internal2 : public student
{
private:
int sub1,sub2,sub3;
public:
void getinternal2marks(int s1,int s2,int s3)
{
sub1=s1;
sub2=s2;
sub3=s3;
}
void putinternal2marks(void)
{
cout<<"subject1 marks="<<sub1<<endl;
cout<<"subject2 marks="<<sub2<<endl;
cout<<"subject2 marks="<<sub3<<endl;
}
};
void main()
{
internal1 i1;
internal2 i2;
clrscr();
i1.getstuddetails(11,"chinnu");
i1.getinternal1marks(34,45,56);
cout<<"Student Details"<<endl;
i1.putstuddetails();
cout<<"Internal1 marks"<<endl;
i1.putinternal1marks();
i2.getinternal2marks(44,55,66);
cout<<"Internal2 marks"<<endl;
// i2.putstuddetails();
i2.putinternal2marks();
}
Hybrid Inheritance
This form of inheritance combines two or more forms of inheritancei.e.
combination of multiple and multilevel inheritance.
Diagram
//hybrdinh.cpp
//implementation of Hybrid Inheritance
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//base class1
class student
{
//private data members
int rno;
char name[16];
public:
void getstuddetails(void)
{
cout<<"enter roll number and name"<<endl;
cin>>rno>>name;
}
void putstuddetails(void)
{
cout<<" roll number="<<rno<<endl;
cout<<"name ="<<name<<endl;
}
};
void putmarks(void)
{
cout<<"sub1 marks ="<<sub1<<endl;
cout<<"sub2 marks ="<<sub2<<endl;
cout<<"sub3 marks ="<<sub3<<endl;
}
};
//baseclass2
class sports
{
protected:
float sportswtg;
public:
void getsportswtg(float s)
{
sportswtg=s;
}
void putsportswtg(void)
{
cout<<"sports weightage="<<sportswtg<<endl;
}
};
//derived class
class result : public marks,public sports
{
private:
int total;
float avg;
public:
void caluculate(void)
{
total=sub1+sub2+sub3+sportswtg;
avg=total/4;
}
void displayresult(void)
{
putstuddetails();
putmarks();
putsportswtg();
cout<<"total marks ="<<total<<endl;
cout<<"average marks="<<avg<<endl;
}
};
void main()
{
result r; //derived class object
clrscr();
r.getstuddetails();
r.getmarks();
r.getsportswtg(5.0);
r.caluculate();
// r.putstuddetails();
// r.putmarks();
clrscr();
r.displayresult();
}
Multipath Inheritance - creation of class from other super class which are derived from common
super class
It is the inheritance where all three kinds of inheritance namely multiple, multilevel and hierarchical
inheritance are involved.
Grandparent
Parent1 parent2
Child
The child has two “direct base classes” i.e. “parent1” and “parent2” which themselves have a common
base class “grandparent”. The child inherits the properties of “grandparent” via two separate paths i.e.
parent1 and parent2. It can also inherit directly as shown above by the broken line. The “grandparent” is
referred as “indirect base class”.
Inheritance by the “child” as shown above cause certain problems. All the public & protected members of
“grandparent” are inherited into “child” twice, first via “parent1” and again via “parent2”. This means,
“Child” would have duplicate set of members inherited from “grandparent”. This introduces ambiguity
and should be avoided.
Note : The dotted line indicates that D inherits from A indirectly
//multipath.cpp
//implementation of Multipath Inheritance
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void putmarks(void)
{
cout<<"sub1 marks ="<<sub1<<endl;
cout<<"sub2 marks ="<<sub2<<endl;
cout<<"sub3 marks ="<<sub3<<endl;
}
};
//intermediate baseclass2
class sports : public student
{
protected:
float sportswtg;
public:
void getsportswtg(float s)
{
sportswtg=s;
}
void putsportswtg(void)
{
cout<<"sports weightage="<<sportswtg<<endl;
}
};
//derived class
class result : public marks,public sports
{
private:
int total;
float avg;
public:
void displayresult(void)
{
total=sub1+sub2+sub3+sportswtg;
avg=total/4;
putstuddetails();
putmarks();
putsportswtg();
cout<<"total marks ="<<total<<endl;
cout<<"average marks="<<avg<<endl;
}
};
void main()
{
result r; //derived class object
clrscr();
r.getstuddetails();
r.getmarks();
r.getsportswtg(5.0);
r.displayresult();
}
O/p displays error as result as child is inheriting duplicate set of properties of student twice via marks and
sports.
//mltpthvr.cpp
//implementation of Multipath Inheritance using virtual base classes
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void putmarks(void)
{
cout<<"sub1 marks ="<<sub1<<endl;
cout<<"sub2 marks ="<<sub2<<endl;
cout<<"sub3 marks ="<<sub3<<endl;
}
};
//intermediate baseclass2
class sports : public virtual student
{
protected:
float sportswtg;
public:
void getsportswtg(float s)
{
sportswtg=s;
}
void putsportswtg(void)
{
cout<<"sports weightage="<<sportswtg<<endl;
}
};
//derived class
class result : public marks,public sports
{
private:
int total;
float avg;
public:
void displayresult(void)
{
total=sub1+sub2+sub3+sportswtg;
avg=total/4;
putstuddetails();
putmarks();
putsportswtg();
cout<<"total marks ="<<total<<endl;
cout<<"average marks="<<avg<<endl;
}
};
void main()
{
result r; //derived class object
clrscr();
r.getstuddetails();
r.getmarks();
r.getsportswtg(5.0);
r.displayresult();
}
Polymorphism
It is one of the important features of OOPs which means “one name, multiple forms”. It is the ability
to take more than one form.
Types of polymorphism
1. Compile-time polymorphism
2. Run-time polymorphism
Compile-time polymorphism
The overloaded functions are “Selected” for invoking by matching arguments, both type and
number. This information is known to the compiler at the compile time and, therefore, compiler is able to
select the appropriate function for a particular call at the compile time itself. This is called early binding
or static binding or static linking. Early binding simply means that an object is bound to its function
call at runtime.
Compile-time polymorphism can be achieved in C++ using the concepts
- Function overloading
- Operator overloading
Function overloading
Overloading refers to performing many tasks by single person.
Function overloading refers to calling a function having same name many number of times but
performing different set of activities and the same is identified by the compiler depending on the number
and type of arguments.
//funcover.cpp
//function overloading
//addition of 2 characters, 2 integers & 2 floating values
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
//function prototyping
char add(char,char);
int add(int,int);
float add(float,float);
//calling a function
//call by value
p=add(a,b);
q=add(c,d);
r=add(e,f);
cout<<"additon of"<<a<<" + "<<b<<" is :"<<p<<endl;
cout<<"additon of"<<c<<" + "<<d<<" is :"<<q<<endl;
cout<<"additon of"<<e<<" + "<<f<<" is :"<<r<<endl;
return(0);
}
//integer additon
int add(int m,int n)
{
return(m+n);
}
//floating addition
float add(float r,float s)
{
return(r+s);
}
Example : 2
//funcover1.cpp
//function overloading
//drawing lines in different designs
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
//function prototyping
void line(void);
void line(char);
void line(int);
void line(char,int);
//main or calling program
main()
{
clrscr();
//calling a function
//call by value
line();
line('*');
line(70);
line('=',80);
return(0);
}
cout<<"-";
}
cout<<endl;
}
void line(char x)
{
for(int i=1;i<=60;i++)
{
cout<<x;
}
cout<<endl;
}
void line(int m)
{
for(int i=1;i<=m;i++)
{
cout<<"+";
}
cout<<endl;
}
Operator overloading
Operator overloading refers to giving additional/special meaning to an operator.
Syntax:
//ovrlodum.cpp
//overloading of unary minus operator
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class unaryminus
{
//private data members
int a,b,c;
public:
//getting data
void getdata(int p,int q,int r)
{
a=p;
b=q;
c=r;
}
// putting data
void putdata(void)
{
cout<<"value of a="<<a<<endl;
cout<<"value of b="<<b<<endl;
cout<<"value of c="<<c<<endl;
}
void main()
{
unaryminus um; //object
clrscr();
um.getdata(5,-10,15);
cout<<"Before overloading unary minus operator"<<endl;
um.putdata();
-um; //overlaoding unary minus - operator
cout<<"After overloading unary minus operator"<<endl;
um.putdata();
}
//ovrlodui.cpp
//overloading of unary pre increment operator
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class unaryincrement
{
//private data members
int a,b,c;
public:
//getting data
void getdata(int p,int q,int r)
{
a=p;
b=q;
c=r;
}
// putting data
void putdata(void)
{
cout<<"value of a="<<a<<endl;
cout<<"value of b="<<b<<endl;
cout<<"value of c="<<c<<endl;
}
void main()
{
unaryincrement uin; //object
clrscr();
uin.getdata(5,-10,15);
cout<<"Before overloading unary pre increment operator"<<endl;
uin.putdata();
++uin; //overloading unary pre increment operator
cout<<"After overloading unary pre increment operator"<<endl;
uin.putdata();
}
Example:
binary +, binary - , binary *, binary *
//ovrlodbp.cpp
// binary operator over loading (+)
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class demo
{
private:
int a;
public:
void read()
{
cout<<"enter a value"<<endl;
cin>>a;
}
void print()
{
cout<<"a ="<<a<<endl;
}
demo operator +(demo b)
{
demo res;
res.a=a+b.a;
return res;
}
};
void main()
{
demo a,b;
clrscr();
a.read( );
b.read( );
a=a+b; //operator overloading function
a.print( );
}
Run-time polymorphism
A member function can be selected while the program is running. This is known as run-time
polymorphism. C++ supports a mechanism known as virtual functions to achieve runtime polymorphism.
Since the function is linked with a particular class much later after the compilation, this process is termed
as late binding. It is also known as dynamic binding because the selection of the appropriate function call
is done dynamically at runtime.
Pointers
It is a variable that holds the address of another variable.
Example:
item x;
Where item is a class and x is an object of type class item
Similarly, we can define a pointer of type class item
Example:
item *itptr; //object pointer
Object pointers are useful in creating objects at run time. We can also use an object pointer to access the
public members of an object.
We can refer the member functions of item in 2 ways, one by using dot operator and the object, and
another by using the arrow operator and the object pointer.
1) x.getdata(5,10);
x.show ();
(*itptr).show ();
//ptrtoobj.cpp
//baseptr.cpp
//pointer to objects (Base Class)
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class item
{
//private data members
int icode;
float price;
public:
void getitemdetails(int a,float b)
{
icode=a;
price=b;
}
void putitemdetails(void)
{
cout<<" item code ="<<icode<<endl;
cout<<" price of item ="<<price<<endl;
}
};
void main()
{
item x,*ptr; //declaration of pointer ptr of type class item
ptr=&x; //initialising the address of object to pointer ptr
clrscr();
//x.getitemdetails(11,100);
//x.putdetails();
ptr->getitemdetails(11,100);
//ptr->putitemdetails();
(*ptr).putitemdetails();
}
Pointers to Derived Classes
Pointers can be used not only to the base class but also to the derived classes. Pointers to objects
of a base class are type compatible with pointers to objects of derived class. Therefore, a single pointer
variable can be made to point to objects belonging to different classes.
For example, if B is a base class and D is a derived class from B, then a pointer declared
as a pointer to B can also be a pointer to D.
However, there is a problem in using bptr to access the public members of the derived class D.
Using bptr, we can access only those members inherited from B and not the members that originally
belonging to D.
NOTE:
- In case a member of D has the same name as one of the members of B, then any reference to
that member by bptr will always access the base class member.
- Although C++ permits a base pointer to point to any object derived from that base, the
pointer cannot be directly used to access all the members of the derived class. In that case, we
have to use anotherpointer declared as pointer to the derived type.
NOTE:
Though a base pointer can be made to point to any number of derived objects, it cannot directly
access the members defined by a derived class.
//dervdptr.cpp
//pointer to derived class objects
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//base class
class base
{
public:
int b;
void show(void)
{
cout<<"value of base class b="<<b<<endl;
}
};
//derived class
class derived : public base
{
public:
int d;
void show(void)
{
cout<<"value of base class b="<<b<<endl;
cout<<"value of derived class d="<<d<<endl;
}
};
void main()
{
clrscr();
//base class
base bb; //base class object
base *bptr; //base class pointer
bptr=&bb; //base class pointer pointing to address of base class object
//derived class
derived dd; //derived class object
bptr=ⅆ //baseclass pointer pointing to the address of derived class object
bptr->b=20; //accessing base class member b thru base class pointer
/* bptr->d=25; */ // accessing derived class member d thru base class
//pointer which does not work
cout<<"base class pointer bptr now points to derived class object"<<endl;
Virtual functions
Though, the base class pointer is pointed to the derived class objects, it executes the function in
the base class but not from the derived class. This problem can be avoided using the concept called
“virtual functions”.
When a function with same name is declared in both the base and derived classes, the function in
base class is declared as virtual, C++ determines which function to be called at run time based on the type
of the object pointed by the pointer, rather than the type of the pointer. Thus, by making the pointer to
point to different objects.
#include<iomanip.h>
//base class
class base
{
public:
int b;
void virtual show(void)
{
cout<<"iam in base class"<<endl;
cout<<"value of base class b="<<b<<endl;
}
};
//derived class
class derived : public base
{
public:
int d;
void virtual show(void)
{
cout<<"iam in derived class"<<endl;
cout<<"value of base class b="<<b<<endl;
cout<<"value of derived class d="<<d<<endl;
}
};
void main()
{
clrscr();
//derived class
derived dd,*dptr; //derived class object
dptr=ⅆ //derivedclass pointer pointing to the address of derived class object
dptr->b=20; //accessing base class member b thru derived class pointer
dptr->d=25; // accessing derived class member d thru derived class pointer
dptr->show();
}
Operator Overloading
The mechanism of giving special meaning to an operator is known as operator overloading.
Note: All the operators of C++ can be overloaded except the following
-
Operators that cannot be overloaded
. Class member access operators (. *)
. Scope resolution operator (:: )
. Size operator (size of)
. Conditional operator (? And :)
Additional task to an operator can be specified with the help of a special function called operator
functionwhich describes the task.
Syntax:
Steps
Process of overloading involves the following steps
1. First, create a class that defines the data types that is to be used in the overloading operation
2. Declare the operator function operator op ( ) in the public part of the class. It may be either a
member function or a friend function
3. Define the operator function to implement the required operations
Operator
It is symbol to perform an operation.
Types of operators
1. Unary operators
2. Binary operators
3. Ternary operators
Unary operators
Unary operators are those operators which takes single operator to perform an operation.
Example:
unary + (plus)
unary – (minus)
increment operator - ++
decrement operator - --
class unaryminus
{
//private data members
int a,b,c;
public:
//getting data
void getdata(int p,int q,int r)
{
a=p;
b=q;
c=r;
}
// putting data
void putdata(void)
{
cout<<"value of a="<<a<<endl;
cout<<"value of b="<<b<<endl;
cout<<"value of c="<<c<<endl;
}
void main()
{
unaryminus um;
clrscr();
um.getdata(5,-10,15);
cout<<"Before overloading unary minus operator"<<endl;
um.putdata();
-um; //overlaoding unary minus - operator
cout<<"After overloading unary minus operator"<<endl;
um.putdata();
}
Binary Operators
These are those operators which takes two operands for operation.
Ex: a+b;
a-b;
//addition of 2 times
//function with object as argument and with return value
//overloading binary plus operator
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class time
{
//private data members
int hours,minutes;
public:
//getting time
void gettime(int h,int m)
{
hours=h;
minutes=m;
}
//displaying time
void puttime(void)
{
cout<<" hours = "<<hours<<" and minutes ="<<minutes<<endl;
}
//overldbp.cpp or ovrlodb.cpp
//addition of 2 times
// binary plus operator overloading function definition
time operator + (time t2)
{
time t;
t.minutes=minutes+t2.minutes;
t.hours=t.minutes/60;
t.minutes=t.minutes%60;
t.hours=t.hours+hours+t2.hours;
return t;
}
};
void main()
{
time t1,t2,t3;
clrscr();
t1.gettime(3,45); //get time1
Inline functions
One of theobjectives of using functions in a program is to save memory space, which
becomes important when a function is likely to be called many times. However, every time a
function is called, it takes lot of time in executing series of instructions for tasks such as jumping
to the function, saving registers, pushing arguments into the stack and returning to the calling
function.
One solution to this problem is to use macro definitions known as macros. But the
drawback of it is that they are not really functions and therefore, the usual error checking does
not occur during compilation.
An inline function is a function that is expanded in inline when it is invoked. That is,
compiler replaces the function call with the corresponding function code.
Syntax:
inline functionheader
{
function body
}
//inlnefnc.cpp
//usage of inline functions
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
float x=9.75;
float y=3.45;
clrscr();
cout<<mult(x,y)<<endl;
cout<<div(x,y)<<endl;
}
Friend Functions
Private data members are not accessible from outside the class. That is, a non member function
cannot have an access to the private data of a class.
There may be a situation where both the classes have to share the common function where in C++
allows the function to be made friendly with both the classes, thereby allowing the function to have
access to the private data of these classes. Such, a function need not be a member of any of these classes.
Functions that are declared with the keyword friend are called friend functions.
Syntax:
Friend returntype functionname(argument list); //declaration
Note:
1. The function declaration should be preceded by the keyword friend and the function is defined
elsewhere in the program like normal function.
2. The function definition does not use either the keyword friend or the scope operator ::
{
//private data members
int a;
public:
void getvalue(int aa)
{
a=aa;
}
//friend function declaration
class two
{
//private data members
int b;
public:
void getvalue(int bb)
{
b=bb;
}
//friend function declaration
void main()
{
one onee;
clrscr();
onee.getvalue(10);
two twoo;
twoo.getvalue(20);
maximum(onee,twoo);
}
C++ uses the concept of stream and stream classes to implement I/O operations with console and
disk files.
C++ Streams
A stream is a sequence of bytes which acts as either as a source from which the input data can be
obtained or as a destination to which the output data can be sent.
The source stream that provides data to the program is called input stream and the destination
stream that receives output from the program is called output stream.
In other words, a program extracts the bytes from an input stream and inserts bytes into an output
stream.
I/O operations
I/O operations are of 2 types namely
1. Unformatted I/O operations
2. Formatted I/O Operations
Syntax:
cin>>variable1>>variable2>>…..variableN;
cout<<item1<<item2<<…..<<itemN;
Example:
int code;
cin>>code;
cout<<code;
2) put() and get() – character oriented functions
The classes istream and ostream define two member functions get() and put() to handle single
character i/o operations.
get() – gets a single character from keyboard
put() – writessingle character onto monitor
ex:
char ch;
cin.get(ch); // gets a character from keyboard and assigns it to variable ch
getline() – reads entire line of text that ends with new line character (enter key)
Syntax:
cin.getline(line,size);
example:
char name[26];
cin.getline(name,25);
example:
cout.write(name,20);
2. Manipulators
These are the parameters that can be included in I/O statements to alter the format parameters
of a stream.
setw() width()
setprecision() precision()
setfill() fill()
setiosflags() setf()
resetiosflags() unsetf()
example:
cout<<width(5);
cout<<123;
cout<<width(5);
cout<<34;
Cout.precison(nod);
Example:
Cout.precison(3);
Cout<<sqrt(3);
Cout.fill(character);
Example:
Cout.fill(‘*’);
Cout.width(5);
Cout<<123;
Working with files (File Management)generally data stored in a variable is temporary and holds only
singleValue at a time and the same is lost whenever system is switched off.
To avoid the problem, external storage devices like hard disks can be used where the data is stored in
these devices using the concept of files.
File is a collection of records or related data stored in a particular area on the disk.
Record is a collection of fields
Field is a collection of characters but should have some meaning.
Streams
Stream is nothing but sequence of bytes. I/O system of C++ handles the file operations (Disk I/O)
which are very much similar to the console I/O operations. It uses file streams to act as interface between
the programs and the files.
File streams
The stream that supplies data to the program is known as input stream
and the one that receives the data from the program is known as output stream.
In other words, the input stream extracts or reads data from the file and the output stream inserts or writes
data to the file.
Opening a file
A file can be opened either for reading/writing data in 2 ways
1. Using the constructor function of the class
2. Using the member function open() of the class
Example :
ofstream outfile(“sample”); // opens file named sample for output only
note : if the file “sample” does not exist, it creates a new file. If exists, it overwrites the contents of
exisiting file.
Example:
ofstream outfile; //creates stream for output
outfile.open(“sample”); //connects stream to sample
outfile.close(); // disconnects stream from sample
//file.cpp
File organization
Specifies how the data in the file is organized.
Ex: while(infile)
An ifstream object, like infile returns a value of 0 if any error occurs in the file operation including the
end of file condition. Thus, the while loop terminates when infile returns a value of 0 on reaching the end
of file condition.
streamobject.open(“filename”,”fileopeningmode”);
The first argc is argument counter which represents the number of arguments in the command line.
The second argument argv is known as argument vector is an array of char type pointers that point to the
command line arguments. The size of the array will be equal to the value of argc.
Example:
C:>evenodd even odd
Here,
the value of argc will be 3
and
the argv would be an array of three pointers to strings as follows
argv[0] -> evenodd
argv[1] -> even
argv[2] -> odd
Note: argv[0] always represent the command name that invokes the program.
int num[10]={11,22,33,44,55,66,77,88,99,100};
if(argc !=3)
{
cout<<"number of arguments="<<argc<<endl;
cout<<"invalid number of arguments passed"<<endl;
exit(1);
}
fout2.open(argv[2]);
if(fout2.fail())
{
cout<<"sorry. cannot open the file"<<argv[2]<<endl;
exit(1);
}
for(int n=0;n<=9;n++)
{
if(num[n]%2 == 0)
fout1<<num[n]<<endl; // as it is even writes to even file
else
fout2<<num[n]<<endl; // as it is odd writes to odd file
}
fout1.close();
fout2.close();
getch();
}
}
Steps :
1. Save the program as cmdline.cpp
2. Compile , link and execute the program by pressing ctrl+f9 which creates
Cmdline.exe file
3. Chose file->dosshell which exit from windows temporarily to dos
4. At the Dos prompt, type C:>cmdline even odd
Templates
Templates allow us to define generic classes which can be used with various data types.
A template can be treated as a macro. When an object of specific type is defined for actual use,
the template definition for that class is substituted with the required data type. Since a template is
defined with a parameter that would be replaced by the special data type at the time of actual use of the
class or function, the templates are sometimes referred as parameterized classes or functions.
Template types
Class templates
Templates allow us to create generic classes. It is a simple process to create a generic class using
a template with an anonymous type.
Syntax:
Template <class T>
Class <classname>
{
// class member specification with anonymous type T wherever appropriate
};
//clstempl.cpp
//working with class templates
#include<iostream.h>
#include<conio.h>
template <class T>
class addition
{
T a,b,sum;
public:
addition()
{
a=b=sum=0;
}
addition(T x,T y)
{
a=x;
b=y;
}
void display(void)
{
cout<<"value of a ="<<a<<endl;
cout<<"value of b ="<<b<<endl;
cout<<" sum is "<<a+b<<endl;
}
void main()
{
addition <int> a1(10,20);
addition <float> a2(3.4,5.7);
int result1;
float result2;
clrscr();
result1=a1.add();
result2=a2.add();
a1.display();
a2.display();
}
Function templates
These are used to create a family of functions with different argument types.
Syntax:
#include<iostream.h>
#include<conio.h>
template <class T>
class highest
{
T a,b;
public:
T highest(T x,T y)
{
return x>y?x:y;
}
};
void main()
{
highest <int> a1(4,5);
highest <float> a2(3.4,5.7);
int result1;
float result2;
clrscr();
result1=a1.highest();
cout<<result1;
result2=a2.highest();
cout<<result2<<endl;
}
Exception Handling
Bug is an error that is encountered during program execution. Whenever an error is encountered,
program is terminated in between without executing in a proper manner. To handle, that situation,
exceptions can be raised known as exception handling mechanism.
Exception handling is the latest feature added to C++. Exceptions refer to unusual conditions in a
program which can be taken care by exception handlers.
Exceptions are of 2 types namely, synchronous and asynchronous exceptions.
The purpose of the exception handling mechanism is to provide means to detect and report an
“exceptional circumstance” so that appropriate action can be taken. The mechanism suggests a separate
error handling code that performs the following tasks:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take necessary actions (Handle the exception)
NOTE:
The error handling code consists of 2 segments; one to detect errors and to throw exceptions and
the other is to catch the exceptions and to take appropriate actions.
C++ uses 3 keywords namely try, catch and throw to handle exceptions.
When a function returns using the exception handling mechanism, it is referred to as throwing an
exception. The keywords “throw” implements this “return” activity.
The keyword try prefaces a block of statements which may generate exceptions.
A catch block defined by the keyword catch “catches” the exceptions “thrown” by throw and
handles them appropriately.