C - 16 Mark
C - 16 Mark
Class:
The building block of C++ that leads to Object-Oriented programming is a Class. It is a
user-defined data type, which holds its own data members and member functions, which
can be accessed and used by creating an instance of that class. A class is like a blueprint
for an object.
● A Class is a user-defined data-type which has data members and member functions.
● Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions
define the properties and behaviour of the objects in a Class.
● In the above example of class Car, the data member will be speed limit, mileage etc
and member functions can apply brakes, increase speed etc.
We can say that a Class in C++ is a blue-print representing a group of objects which
shares some common properties and behaviors.
Object:
An Object is an identifiable entity with some characteristics and behaviour. An
Object is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated.
class person
{
char name[20];
int id;
public:
void getdetails(){}
};
int main()
{
person p1; // p1 is a object
}
Object take up space in memory and have an associated address like a record in pascal or
structure or union in C.
When a program is executed the objects interact by sending messages to one another.
Each object contains data and code to manipulate the data. Objects can interact without
having to know details of each other’s data or code, it is sufficient to know the type of
message accepted and type of response returned by the objects.
Encapsulation:
In normal terms, Encapsulation is defined as wrapping up of data and information
under a single unit. In Object-Oriented Programming, Encapsulation is defined as binding
together the data and the functions that manipulate them.
Encapsulation also leads to data abstraction or hiding. As using encapsulation also hides
the data. In the above example, the data of any of the section like sales, finance or
accounts are hidden from any other section.
Abstraction:
Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.
Polymorphism:
The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than one form.
A person at the same time can have different characteristic. Like a man at the same time
is a father, a husband, an employee. So the same person posses different behaviour in
different situations. This is called polymorphism.
An operation may exhibit different behaviours in different instances. The behaviour
depends upon the types of data used in the operation.
C++ supports operator overloading and function overloading.
● Operator Overloading: The process of making an operator to exhibit different
behaviours in different instances is known as operator overloading.
● Function Overloading: Function overloading is using a single function name to
perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some integers, sometimes there are
2 integers; sometimes there are 3 integers. We can write the Addition Method with the
same name having different parameters; the concerned method will be called according to
parameters.
Inheritance:
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.
● Sub Class: The class that inherits properties from another class is called Sub class
or Derived Class.
● Super Class:The class whose properties are inherited by sub class is called Base
Class or Super class.
● Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Dynamic Binding:
In dynamic binding, the code to be executed in response to function call is decided
at runtime. C++ has virtual functions to support this.
Message Passing:
Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure and
therefore will invoke a function in the receiving object that generates the desired results.
Message passing involves specifying the name of the object, the name of the function and
the information to be sent.
Include files
1. Documentation Section
In Documentation section we give the Heading and Comments. Comment
statement is the non-executable statement. Comment can be given in two ways:
(i) Single Line Comment: Comment can be given in single line by using "II".
The general syntax is: II Single Text line
(ii) Multiple Line Comment: Comment can be given in multiple lines starting by
using "/*" and end with "*/".
2. Preprocessor Directives
Pre-compiler statements are divided into two parts.
(i) Link Section:
In the Link Section, we can link the compiler function like cout<<, cin>>,
sqrt ( ), fmod ( ), sleep ( ), clrscr ( ), exitO, strcatO etc.
ii) Definition Section:
The second section is the Definition section by using which we can define a
variable with its value. For this purpose define statement is used.
3. Global Declaration Section
Declare some variables before starting of the main program or outside
the main program. These variables are globally declared and used by the main
function or sub function
Class declaration or definition
A class is an organization of data and functions which operate on them. Data types are
called data members and the functions are called member functions. The combination of
data members and member functions constitute a data object or simply an object.
main function is where a program starts execution. Main () program is the C++
program's main structure in which we process some statements. The main function
usually organizes at a high level the functionality of the rest of the program.
The general syntax is: main ( )
1. Beginning of the Main Program: Left Brace {
(The beginning of the main program can be done by using left curly brace "{").
(i) Object declaration part
We can declare objects of class inside the main program or outside the main
program.
For example: b1 is the object of the class book. We can create any number of
objects of a given class.
UNIT -2
C++ Tokens
A token is the smallest element of a program that is meaningful to the compiler.
Tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keyword:
Keywords are those words whose meaning is already defined by Compiler.
These keywords cannot be used as an identifier. Note that keywords are the collection
of reserved words and predefined identifiers..Every Keyword exists in lower case
While in C++ there are 31 additional keywords other than C Keywords they
are:
asm bool catch class
const_cast delete dynamic_cast explicit
export false friend inline
mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw
true try typeid typename
using virtual wchar_t
2. Identifiers:
Identifiers are used as the general terminology for naming of variables,
functions and arrays. These are user defined names consisting of 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.
NAME REMARK
_A9 Valid
Invalid as it contains special character other than the
Temp.var underscore
void Invalid as it is a keyword
1. Constants:
Constants are also like normal variables. But, 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 as literals.
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”
2. 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++.
1. 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 marks 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.
● semi colon : It is an operator that essentially invokes something called an
initialization list.
● asterick (*): It is used to create 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.
2. Operators:
Operators are symbols that triggers 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 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 Operators
Ternary Operators: These operators requires three operands to act upon.
For Example Conditional operator(?:).
For more information about operators
2. Control Structure in C++
A control structure is a block of programming that analyzes variables
and chooses a direction in which to go based on given parameters. The term
flow control details the direction the program takes
1.Branching
2.Looping
Branching statement
⮚ if statement
⮚ if..else statements
⮚ if-else-if ladder
⮚ nested if statements
⮚ switch statements
If Statement:
Syntax
if (condition)
{
statement 1;
statement 2;
statement 3;
}
Example
if (mark>40)
{
Cout<<”PASS”;
}
If-else Statement:
Syntax
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example
if(x>y)
cout<<”X is greater”;
else
cout<<”y is greater”;
if-else-if ladder
The if-else-if staircase, has an if-else statement within the outermost else
statement. The inner else statement can further have other if-else statements. As
soon as one of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed
Syntax
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Example
char ch;
cout<<"Enter an alphabet:";
cin>>ch;
if( (ch>='A') && (ch<='Z'))
cout <<"The alphabet is in upper
case";
else if ( (ch>=' a') && (ch<=' z' ) )
cout<<"The alphabet is in lower
case";
else
cout<<"It is not an alphabet";
return 0;
}
for Loop
for(initializationStatement;
testExpression;increment/decrement
)
// codes
}
Example
for(i=0;i<=5;i++)
while Loop
The do...while loop is a variant of the while loop with one important difference.
The body of do...while loop is executed once before the test expression is checked.
● The codes inside the body of loop is executed at least once. Then, only the
test expression is checked.
● If the test expression is true, the body of loop is executed. This process
continues until the test expression becomes false.
● When the test expression is false, do...while loop is terminated.
Syntax
do
{
// codes;
}
while (testExpression);
Example
do
{
Cout<<”SRM IST “;
}
while (i<=5);
Example Program
3. Datatypes in C++
1. Primary(Built-in) Data Types:
⮚ character
⮚ integer
⮚ floating point
⮚ boolean
⮚ double floating point
⮚ void
⮚ wide character
⮚ Structure
⮚ Union
⮚ Class
⮚ Enumeration
3.Derived Data Types:
⮚ Array
⮚ Function
⮚ Pointer
The data types that are defined by the user are called the derived datatype or
user-defined derived data type.
Class:
The building block of C++ that leads to Object Oriented
programming is a Class. It is a user defined data type, which holds its own data
members and member functions, which can be accessed and used by creating an
instance of that class. A class is like a blueprint for an object.
Structure:
A structure is a user defined data type in C/C++. A structure
creates a data type that can be used to group items of possibly different types into a
single type.
Syntax
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Union:
Syntax
union address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Enumeration:
Syntax
enum week
{
Mon,
Tue,
Wed,
Thur,
Fri,
Sat,
Sun
};
2.Built in Data Type
Data types in C++ is mainly divided into two types: Primitive Data Types:
These data typesare built-in or predefined data types and can be used directly by
the user to declare variables. example: int, char , float, bool etc.
:
These data types are built-in or predefined data types and can be used
directly by the user to declare variables. example: int, char , float, bool etc.
Integer: Keyword used for integer data types is int. Integers typically
requires 4 bytes of memory space and ranges from -2147483648 to 2147483647.
Character: Character data type is used for storing characters. Keyword used
for character data type is char. Characters typically requires 1 byte of memory
space and ranges from -128 to 127 or 0 to 255.
Boolean: Boolean data type is used for storing boolean or logical values. A
boolean variable can store either true or false. Keyword used for boolean data type
is bool.
Floating Point: Floating Point data type is used for storing single precision
floating point values or decimal values. Keyword used for floating point data type
is float. Float variables typically requires 4 byte of memory space.
Double Floating Point: Double Floating Point data type is used for storing
double precision floating point values or decimal values. Keyword used for double
floating point data type is double. Double variables typically requires 8 byte of
memory space.
void: Void means without any value. void datatype represents a valueless
entity. Void data type is used for those function which does not returns a value.
1. Array
2. Function
3. Pointer
Array
An array is simply a collection of variables of the same data
type that are referenced by a common name. In other words, when elements of
linear structures are represented in the memory by means of contiguous memory
locations, these linear structures are called arrays.
Syntax
type array_name[array_size];
Example
Int arr[10];
Functions
A function declaration tells the compiler about a function's name, return
type, and parameters. A function definition provides the actual body of the
function. The C++ standard library provides numerous built-in functions that your
program can call.
Function prototype or function interface is a declaration of
a function that specifies the function's name and type signature (arity, data types
of parameters, and return type), but omits the function body.
Syntax
Function name ()
{
--------
--------
}
Pointers
& symbol is used to get the address of the variable. * symbol is used
to get the value of the variable that the pointer is pointing to. If a pointer in C is
assigned to NULL, it means it is pointing to nothing. Two pointers can be
subtracted to know how many elements are available between these two pointers.
The actual data type of the value of all pointers, whether integer,
float, character, or otherwise, is the same, a long hexadecimal number that
represents a memory address. The only difference between pointers of
different data types is the data type of the variable or constant that
the pointer points to.
Syntax
Int *a
4.Operators in C++
An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. C++ is rich in built-in operators and provide the following types
of operators −
● Arithmetic Operators
● Relational Operators
● Logical Operators
● Bitwise Operators
● Assignment Operators
Arithmetic Operators
Relational Operators
Logical Operators
Operato Description Example
r
Bitwise Operators
Operator Description Example Operator Description
Assignment Operators
Operato Description Example
r
Misc Operators
Sr.No Operator & Description
1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer,
and will return 4.
2 Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise returns
value of Y.
3 ,
Comma operator causes a sequence of operations to be performed. The value of the entire
comma expression is the value of the last expression of the comma-separated list.
5 Cast
Casting operators convert one data type to another. For example, int(2.2000) would return 2.
6 &
Pointer operator & returns the address of a variable. For example &a; will give actual
address of the variable.
7 *
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.
Unit 3
1.Functions in C++
A function is a group of statements that together perform a task.
Every C++program has at least one function, which is main(), and all the most
trivial programs can define additional functions. ... A function declaration tells the
compiler about afunction's name, return type, and parameters.
Syntax:
// function-body
● return-type: suggests what the function will return. It can be int, char, some
pointer or even a class object. There can be functions which does not return
anything, they are mentioned with void.
● Function Name: is the name of the function, using the function name it is
called.
● Parameters: are variables to hold values of arguments passed while
function is called. A function may or may not contain parameter list.
● Function body: is the part where the code statements are written.
Calling a Function
Functions are called by their names. If the function is without argument, it can
be called directly using its name. But for functions with arguments, we have two
ways to call them,
1. Call by Value
2. Call by Reference
Call by Value
In this calling technique we pass the values of arguments which are stored or
copied into the formal parameters of functions. Hence, the original values are
unchanged only the parameters inside function changes.
Example
void calc(int x);
int main()
int x = 10;
calc(x);
printf("%d", x);
void calc(int x)
x = x + 10 ;
Call by Reference
In this we pass the address of the variable as arguments. In this case the
formal parameter can be taken as a reference or a pointer, in both the case they will
change the values of the original variable
Example
void calc(int *p);
int main()
int x = 10;
printf("%d", x);
*p = *p + 10;
Main Function
The main( ) function in a C++ program is typically a non value returning
function (a void function). A void function does not return a value to its caller.
the main function is "called" by the operating system when the user runs the
program.
Syntax:
Void main
---------
-----------
Default arguments
2.FUNCTION OVERLOADING
Function overloading is a feature in C++ where two or more functions can have
the same name but different parameters. Function overloading can be considered as an
example of polymorphism feature in C++
Two or more functions having same name but different argument(s) are
known as overloaded functions.
FUNCTION OVERLOADING
Function Overloading is when multiple function with same name exist in a
class. Function Overriding is when function have same prototype in base class as
well as derived class. Function overloading is a compile-time polymorphism.
Rules
● The same function name is used for more than one function definition
● The functions must differ either by the arity or types of their parameters
●
Example
Class aaa
Sum(float x,int z)
Example Program
#include <iostream>
class Addition
public:
return num1+num2;
return num1+num2+num3;
};
int main(void)
Addition obj;
cout<<obj.sum(20, 15)<<endl;
return 0;
FUNCTION OVERRIDING
Example
int test() { }
int test(int a) { }
float test(double a) { }
#include <iostream.h>
class printData
{
public:
void print(int i)
{
cout << "Printing int: " << i << endl;
}
void print(double f)
{
cout << "Printing float: " << f << endl;
}
void print(char* c)
{
cout << "Printing character: " << c << endl;
}
};
int main()
{
printData pd;
pd.print(5);
pd.print(500.263);
pd.print("Hello C++");
return 0;
}
OUTPUT
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
3.Class and object
Class
C++ Classes and Objects. Class: The building block of C++ that leads
to Object Oriented programming is a Class. It is a user defined data type, which
holds its own data members and member functions, which can be accessed and
used by creating an instance of that class.
Syntax
Class class_name
Example
Class bca
Class_name object-name
Example
Bca aa;
Member function Definition
class bca
{
public :
int a,b,c:;
sum() // function definition
{
c=a+b;
}
};
Outside class
class bca
{
public :
int a,b,c:;
sum() // function Declaration
};
void bca :: sum() // function definition
{
c=a+b;
}
To define a member function outside the class definition we have to use the
scope resolution :: operator along with class name and function name.
Array of object
● Like array of other user-defined data types, an array of type class can also be
created.
● The array of type class contains the objects of the class as its individual elements.
● Thus, an array of a class type is also known as an array of objects.
● An array of objects is declared in the same way as an array of any built-in data
type.
Syntax
class class-name
datatype var1;
datatype varN;
method1();
method2();
methodN();
};
Example
Class aaa
Void main()
{
Aaa a1[5] // array of object
Example program
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
Classemp
{
inteid;
doublehra, pf, da, cca, nf, bp;
charename[10];
public:
voidgetdata()
{
cout<<”enter name of the employee:”<<endl;
gets(name);
cout<<”enter employee id:”<<endl;
cin>>eid;
cout<<”enter employee basic pay:”<<endl;
cin>>bp;
}
void allow()
{
hra=(bp*10)/100;
pf=(bp*12)/100;
da=(bp*11)/100;
cca=(bp*8)/100;
np=(bp+hra+da+cca)-pf;
}
Voidputdata();
{
cout<<”employee name is:”<<ename<<endl;
cout<<”employee id is:”<<eid<<endl;
cout<<”employee basic pay is:”<<bp<<endl;
cout<<”\nhra=”<<hra<<”\n da=”<<da<<”\n pf=”<<pf<<”\n
cca=”<<cca;
cout<<”\n net pay of employee is:”<<np<<endl;
}
};
void main()
{
clrscr();
int n;
emp e[100];
cout<<”\n \t Arrays Of Objects”;
cout<<”\n enter number of employees:”<<endl;
cin>>n;
for(inti=0;i<n;i++)
{
cout<<”entering the details of employee:”<<i+1<<endl;
e[i].getdata();
e[i].allow();
}
clrscr();
for(inti=0;i<n;i++)
{
cout<<”displaying details of employee:”<<i+1<<endl;
e[i].putdata();
cout<<endl;
}
getch();
}
OUTPUT:
Arrays Of Objects
Syntax
friend function-name()
Example
class Box
double a;
public:
double b;
friend sum();
};
Example Program:
#include <iostream.h>
class B;
class A
{
private:
int numA;
public:
A(): numA(12) { }
friend int add(A, B);
};
class B
{
private:
int numB;
public:
B(): numB(1) { }
friend int add(A , B);
};
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}
int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
5. Constructor and Destructorin C++
The 'calling part' is performed automatically whenever a new Object of the class
is created. Constructors can be used for efficient memory management, which is
not possible with functions. Destructor can be used to destroy
the constructors when not needed.
Syntax:
Class classname
public:
class Name()
{
//set fields and call methods
}
Example
Class bca
{
Bca ()
{
Cout << “Welcome;
}
};
Void main()
{
Bca b; // Constructor will call Automatically
}
Constructor overloading
Constructor overloading in C++ programming is same as function overloading.
When we create more that one constructors in a class with different number of parameters
or different types of parameters or different order of parameters, it is called as constructor
overloading
Types of Constructor
⮚ Default Constructor.
⮚ Parameterized Constructor.
⮚ Copy Constructor.
Default Constructor.
constructor_name ( ) ; // Declaration
{
------ // Body of the constructor
}
Parameterized constructor
Syntax
{
------ // Body of the constructor
}
Copy Constructor
Such constructor having reference to the object of its own class is known as
copy constructor. It creates a new object as a copy of an existing object.
Syntax
class class_name{
public:
class_name(class_name & obj)
{
// obj is same class another object
// Copy Constructor code
}
//... other Variables & Functions
}
Example
Main ()
{
class_name object1(params);
Method 1 - Copy Constrcutor
class_name object2(object1);
Method 2 - Copy Constrcutor
class_name object3 = object1;
}
Destructor
A destructor is a member function with the same name as its class prefixed
by a ~ (tilde).
A destructor is a special method called automatically during the destruction
of an object. Actions executed in the destructor include the following: Recovering
the heap space allocated during the lifetime of an object.
Basically Constructor is used to initialize the objects (at the time of
creation), and they are automatically invoked. This saves us from the garbage
values assigned to data members; during initializing.
Syntax:
Class class_name
{
public:
~class_name() //Destructor
{
}
}:
Example
Class bca
{
public:
~bca() //Destructor
{
}
}:
Unit 4
1 -Inheritance
Sub Class: The class that inherits properties from another class is called Sub
class or Derived Class.
Super Class: The class whose properties are inherited by sub class is called
Base Class or Super class.
Syntax
!.Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
Single Inheritance
Single Inheritance have One base class and One derived class C++ single
inheritance only one class can be derived from the base class. Based on the
visibility mode used or access specify used while deriving, the properties of the
base class are derived. Accesses specify can be private, protected or public.
Diagram
Example
{ ..........
};
{ ...........
};
Multilevel Inheritance
(One Base - One Derived - One or more than One Intermediate class)
Diagram
class A // base class
{ ...........
};
{ ...........
};
{ ...........
};
Multiple Inheritance
Diagram
Syntax
class A
{..........
};
class B
{ ...........
};
class C : acess_specifier A , access_specifier B // derived class from A and B
{...........
};
Difference between Multilevel and Multiple Inheritance
Hierarchical Inheritance
Diagram
Syntax
class A // base class
{..............
};
class B : access_specifier A // derived class from A
{ ...........
};
class C : access_specifier A // derived class from A
{ ...........
};
class D : access_specifier A // derived class from A
{ ...........
};
Hybrid Inheritance
Combination of More than One type of Inheritance
C++ hybrid inheritance is combination of two or more types of inheritance.
It can also be called multi path inheritance.
The hybrid combination of single inheritance and multiple inheritance.
Hybrid inheritance is used in a situation where we need to apply more than one
inheritance in a program.
Diagram
Syntax
class A
{ .........
};
class B : public A
{ ..........
};
class C
{ ...........
};
class D : public B, public C
{ ...........
};
Example program -Lab Program (9,10,11,12) Any one
2.Virtual Base class
Virtual base class is used in situation where a derived have multiple copies
of base class.
Two or more objects are derived from a common base class, we can prevent
multiple copies of the base class being present in an object derived from those
objects by declaring the base class as virtual when it is being inherited. Such a base
class is known as virtual base class. This can be achieved by preceding the base
class’ name with the word virtual.
Syntax
class A
{
}
class B: Virtual public A //virtual base class
{
}
class C: Virtual public A // virtual base class
{
{
}
class D: public B, public C
{
}
Example Program :
#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};
class ClassB : virtual public ClassA
{
public:
int b;
};
class ClassC : virtual public ClassA
{
public:
int c;
};
class ClassD : public ClassB, public ClassC
{
public:
int d;
};
void main()
{
ClassD obj;
obj.a = 10; //Statement 1
obj.a = 100; //Statement 2
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout<< "\n A : "<< obj.a;
cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d;
Output :
A : 100
B : 20
C : 30
D : 40
3.Virtual Function
Syntax
class class- name
{
public:
virtual function-name()
{
}
};
Example
class bca
{
public:
virtual sum() // virtual function
{
}
};
Example program
#include <iostream.h>
class Bird
{
public:
virtual void features()
{
cout << "Loading Bird features.\n";
}
};
class Parrot : public Bird
{
public:
void features()
{
this->Bird::features();
cout << "Loading Parrot features.\n";
}
};
class Penguin : public Bird
{
public:
void features()
{
this->Bird::features();
cout << "Loading Penguin features.\n";
}
};
class Loader
{
public:
void loadFeatures(Bird *bird)
{
bird->features();
}
};
int main()
{
Loader *l = new Loader;
Bird *b;
Parrot p1;
Penguin p2;
b = &p1;
l->loadFeatures(b);
b = &p2;
l->loadFeatures(b);
return 0;
}
OUTPUT
Loading Bird features.
Loading Parrot features.
Loading Bird features.
Loading Penguin features.
Example
Class student /*abstract class*/
{
Virtual void sum()=0; /*pure virtual function*/
};
Example
class Test // abstract class
{
public:
virtual void show() = 0;
};
Pure virtual function is also known as abstract class.
Example Program
#include<iostream.h>
#include<conio.h>
public:
void Display3()
};
public:
void Display1()
}
void Display2()
};
void main()
DerivedClass D;
Output :
5. This Pointer
C++ this Pointer. Every object in C++ has access to its own address
through an important pointer called this pointer. This pointer is an implicit
parameter to all member functions. ... Friend functions do not have a
this pointer, because friends are not members of a class.
A friend function of a class is defined outside that class' scope but it has the
right to access all private and protected members of the class. Even though the
prototypes for friend functions appear in the class definition, friends are not
member functions.
Uses
‘this’ pointer is a constant pointer that holds the memory address of the
current object. ‘this’ pointer is not available in static member functions as static
member functions can be called without any object (with class name).
The this pointer holds the address of current object, in simple words you
can say that this pointer points to the current object of the class
Example Program:
#include <iostream.h>
class B;
class A
{
private:
int numA;
public:
A(): numA(12) { }
friend int add(A, B);
};
class B
{
private:
int numB;
public:
B(): numB(1) { }
friend int add(A , B);
};
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}
int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
6.Operator overloading
In C++, we can make operators to work for user defined classes. This means C++
has the ability to provide the operators with a special meaning for a data type, this ability
is known as operator overloading.
For example, we can overload an operator ‘+’ in a class like String so that we can
concatenate two strings by just using +.
Overloaded Operators
●
Example Program
#include <iostream.h>
using namespace std;
class IncreDecre
{
int a, b;
public:
void accept()
{
cout<<"\n Enter Two Numbers : \n";
cout<<" ";
cin>>a;
cout<<" ";
cin>>b;
}
void operator--() //Overload Unary Decrement
{
a--;
b--;
}
void operator++() //Overload Unary Increment
{
a++;
b++;
}
void display()
{
cout<<"\n A : "<<a;
cout<<"\n B : "<<b;
}
};
int main()
{
IncreDecre id;
id.accept();
--id;
cout<<"\n After Decrementing : ";
id.display();
++id;
++id;
cout<<"\n\n After Incrementing : ";
id.display();
return 0;
}
UNIT 5
1.C++ Stream classes
In C++ there are number of stream classes for defining various streams
related with files and for doing input-output operations. All these classes are
defined in the file iostream.h.
1. ios class is topmost class in the stream classes hierarchy. It is the base class for istream,
ostream, and streambuf class.
2. istream and ostream serves the base classes for iostream class. The class istream is
used for input and ostream for the output.
3. Class ios is indirectly inherited to iostream class using istream and ostream. To avoid
the duplicity of data and member functions of ios class, it is declared as virtual base class
when inheriting in istream and ostream as
Syantax
};
};
4. The withassign classes are provided with extra functionality for the assignment
operations that’s why _withassign classes.
5. The ios class: The ios class is responsible for providing all input and output facilities
to all other stream classes.
6.The istream class: This class is responsible for handling input stream. It provides
number of function for handling chars, strings and objects such as get, getline, read,
ignore, putback etc..
Example Program
#include <iostream>
using namespace std;
int main()
{
char x;
cout << x;
}
2.C++ stream
C++ comes with libraries which provides us with many ways for performing input and
output. In C++ input and output is performed in the form of a sequence of bytes or more
commonly known as streams.
The most basic stream types are the standard input/output streams: istream cin. built-in
input stream variable; by default hooked to keyboard. ostream cout built-in
output stream variable; by default hooked to console.
● Input Stream: If the direction of flow of bytes is from the device(for example,
Keyboard) to the main memory then this process is called input.
● Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory
to device ( display screen ) then this process is called output.
3.Unformatted I/O
It is a method of cin object used to input a single character from keyboard. But its
main property is that it allows wide spaces and newline character. It is a method of cout
object and it is used to print the specified character on the screen or monitor.
Unformatted Input/Output is the most basic form of
input/output. Unformatted input/output transfers the internal binary representation of the
data directly between memory and the file. Formatted output converts the internal binary
representation of the data to ASCII characters which are written to the output file
1.void get()
It is a method of cin object used to input a single character from keyboard. But its main
property is that it allows wide spaces and newline character.
Syntax:
char c=cin.get();
2.void put()
It is a method of cout object and it is used to print the specified character on the screen or
monitor.
Syntax:
cout.put(variable / character);
This is a method of cin object and it is used to input a string with multiple spaces.
Syntax:
char x[30];
cin.getline(x,30);
It is a method of cout object. This method is used to read n character from buffer variable.
Syntax:
cout.write(x,2);
5.cin
It is the method to take input any variable / character / string.
Syntax:
6.cout
Syntax:
1.width(n)
Syntax:
cout<<setw(int n);
2.fill(char)
Syntax:
cout<<setfill('character')<<variable;
3.precison(n)
Syntax:
cout<<setprecision('int n')<<variable;
4.setflag(arg 1, arg,2)
Syntax:
5. unsetflag(arg 2)
Syntax:
resetiosflags(argument 2);
6.setbase(arg)
Syntax:
setbase(argument);
5.Exception Handling
Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.
● throw − A program throws an exception when a problem shows up. This is done
using a throw keyword.
● catch − A program catches an exception with an exception handler at the place in
a program where you want to handle the problem. The catch keyword indicates
the catching of an exception.
● try − A try block identifies a block of code for which particular exceptions will
be activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords
Syntax
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement.
The operand of the throw statement determines a type for the exception and can be any
expression and the type of the result of the expression determines the type of exception
thrown.
Try
{
// protected code
}
catch()
{
// code to handle ExceptionName exception
}
Example Program
#include <iostream>
if( b == 0 ) {
return (a/b);
int main ()
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
return 0;