Rayalaseema University, Kurnool: Paper-IV: Programming in C and C++ Programming in C: Unit - I
Rayalaseema University, Kurnool: Paper-IV: Programming in C and C++ Programming in C: Unit - I
Rayalaseema University, Kurnool: Paper-IV: Programming in C and C++ Programming in C: Unit - I
Unit – I
Overview of C – Constants, Variables, and Data Types – Managing Input and Output
Operations – Operators and Expressions – Decision Making and Branching Statements –
Decision Making and Looping Statements.
Unit – II
Arrays – Character Arrays and Strings – Functions: Built-in and user-defined Functions –
Structures and Unions – Pointers – Pointer Arithmetic – Pointers to Arrays.
Unit – III
Pointers to Functions and Structures – Linked Lists – Files – Input/Output Operations on
Files – Sequential and Random Access to Files – Command Line Arguments.
Programming in C++ :
Unit – IV
Principles of Object-Oriented Programming – Tokens, Expressions and Control Structures –
Functions in C++ – Classes and Objects.
Unit – V
Constructors and Destructors – Operator Overloading and Type Conversions – Inheritance,
Types of Inheritance – Extending Classes – Pointers, Virtual Functions and Polymorphism.
Reference books:
1. Computing Fundamentals and C Programming : E.Balagurusamy, TMH
2. Object-Oriented programming with C++, 4th Edition : E.Balagurusamy, TMH
Object: Student
DATA
Name
Date-of-Birth
Marks
………………
………………
FUNCTIONS
Total
Average
Display
………………
……………...
2.Classes:We just mentioned that objects contain data and code to manipulate that data. The entire set of
data and code of an object can be made a user defined data type with the help of a class. In fact, objects
are variables of the type class. Once a class has been defined, we can create any number of objects
belonging to that class. Each object is associated with the data of type class with which they are created.
A class is thus a collection of objects of similar type. For example, mango, apple and orange are members
of the class fruit. Classes are user defined data types and behave like the built – in – types of a
programming language. The syntax used to create an object is no different than the syntax used to create
an integer object in C. If fruit has been defined as a class, then the statement
Fruit mango;
Will create an object mango belonging to the class fruit
Attributes Attributes
…………………….. ……………………..
………………….... …………………....
…………………….. ……………………..
5.Polymorphism:
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability
to take more than one form. An operation may exhibit different behaviors in different instances. The
behavior depends upon the types of data used in the operation. For example, consider the operation of
addition. For two numbers, the operation will generate a sum. If the operands are strings, then the
operation would produce a third string by concatenation. The process of making an operator to exhibit
different behaviors in different instances is known as operator over loading.
Figure illustrates that a single function name can be used to handle different number and different
types of arguments. This is something similar to a particular word having several different meanings
depending on the context. Using a single function name to perform different types of tasks is known as
function over loading.
Shape
Draw ( )
6.Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding (also known as late binding) means that the code associated with a given procedure call
is not known until the time of the call at run – time. It is associated with polymorphism and inheritance
7.Message passing:
An object – oriented program consists of a set of objects that communicate with each other. The
process of programming in an object – oriented language, therefore, involves the following basic steps:
1. Creating classes that define objects and their behavior
2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the same way
as people pass messages to one another. The concept of message passing makes it easier to talk about
building systems that directly model or simulate their real-world counterparts.
Example:
1. Declaring Structure
2. Declaring Class
3. Declaring Variable
.
Classes declaration section:- In C++ all the data items and functions which are used in the program can
be included in the class declaration section. The class contains set of data items are known as instance
variables.
“Class” Starts with a key word “Class’
Ex: class student
{
data;
fun();
};
Syntax:
class name
{
Private:
data members;
member functions;
Public:
data members;
member functions
};
Functions definition section:- We can write code for all functions which are declared in different
classes. The code is independent for each function depending on the task perform by that function. These
functions are called member functions.
The code under these functions is invoked them then function call make with the help of object
in the main program.
Main function selection (or) program:- Every C++ program have one “main( )”. The compiler begins
the execution of a program from main( ) only. For accessing the instances variables the objects are
created in the main program.
CONTROL STATEMENTS:
Control statements are used to control the flow of a program according to the condition or requirement in
a loop. These are mainly two types of control statements.
1. Branching.
2. Looping.
1.Branching statements:- It is also called as decision making statement. The various branching statements
are.
i)If—statement:- The If statement is the powerful decision making statement which can handle a
single condition or a group of statements. When only one condition occurs in a statement, “Simple-if”
statement is used.
Syntax for simple if:-
if (condition)
{
statement-1;
statement-2;
}
Statement-x;
If the expression is true then the statements immediately following “if” are executed. Otherwise
control passes through the next statement.
W.A.P to find if you are in teenage usage “simple if”.
# include < stdio.h >
main( )
{
int age;
cout<< “Enter your age” << end l;
cin>> age;
if ((age>=13) && (age<=19))
{
Cout<< “ u r in teenage” <<age;
}
}
ii) if else
If block sometimes is followed with the optional else block. When the if condition becomes false then
else block gets executed.
Syntax:-
if(condition)
{
Statement-1;
Statement-2;
-------------
-------------
}
else
{
statement-3;
}
Ex:-Wap to find if the student is passed or not using if else
#include <iostream.h>
int main ()
{
// declare local variable
int marks = 30;
return 0;
}
:- A multi way decision can be written by using if-else constraints in the else part.
If expression is true whole chain is terminated. Only if expression 1 is false the chain will
continue, at any stage. If an expression is true, the remaining chain will be terminated.
Syntax:-
if(boolean_expression 1)
{
// When expression 1 is true
}
else if( boolean_expression 2)
{
// When expression 2 is true
}
else if( boolean_expression 3)
{
// When expression 3 is true
}
else
{
// When none of expression is true
}
Example: Wap to find the class of the student usinf else if ladder
#include <iostream>
int main ()
{
// declare local variable
int marks = 55;
return 0;
}
iv)Switch case statement:- The switch case statement is the better option than the else if statement. It is
a multi-decision maker. In the switch case statement the condition is tested by the switch statement. It is
followed by the list of cases. Each case have the particular constant value, when a correct match is found
a block of statements associated with that case is executed.
Syntax:-
switch (expression)
{
case < lable 1 > : statement 1;
break;
case < lable 2 > : statement 2;
break;
case <lable n >: statement n;
break;
default: statement-x;
}
W.A.P. to read two numbers and person addition, subtraction,division and multiplication.
# include < iostream.h >
void main ( )
{
int ch, a,b,c;
cout<< “Enter two numbers”;
cin>>a>>b;
cout<< “\n1. Addition \n 2. subtraction \n 3. multiplication \n 4.division\n”);
cout<< “\n Enter ur choice (1.4)\n’;
cin>>ch;
switch(ch)
{
case 1: c=a+b;
cout<< “\n Addition of 2 numbers”<<c;
break;
case 2: c= a-b;
cout<< “\n subtraction of 2 numbers”<<c;
break;
case 3: c=a*b;
cout<< “\n multiplication of 2 numbers”<<c;
break;
case 4: c= a/b;
cout<< “\n division of 2 numbers “<<c;
break;
default: cout<< “\n match is not found”;
}
}
2.LOOPING STRUCRURES:-
i) while loop:- The while loop checks whether the test expression is true or not. If it is true, code/s inside
the body of while loop is executed,that is, code/s inside the braces { } are executed. Then again the test
expression is checked whether test expression is true or not. This process continues until the test
expression becomes false.
Syntax: while(condition)
{
statement;
increment/decrement;
}
W.A.P. to print numbers from 1 to 10 using while loop.
# include < iostream.h >
void main( )
{
int i=1;
while(i<=10)
{
cout<< i<<end l;
i++;
}
}
ii) Do-while:- The do-while is called bottom tested loop or exit control loop The do...while Loop is
similar to while loop with one very important difference. In while loop, check expression is checked at
first before body of loop but in case of do...while loop, body of loop is executed first then only test
expression is checked. That's why the body of do...while loop is executed at least once.
Syntax:-
do
{
statements;
increment/decrement;
} while (condition);
iv) For Loop:- It is a popular and simple loop statement. It is used to reduce source code length. The
initialization statement is executed only once at the beginning of the for loop. Then the test expression is
checked by the program. If the test expression is false, for loop is terminated. But if test expression is true
then the code/s inside body of for loop is executed and then update expression is updated. This process
repeats until test expression is false
Syntax:-
for(initialization statement; test expression; update statement)
{ code/s to be executed;
}
Syntax
goto label;
... ..
... ..
label: statement;
C++ Tokens
As we know that Software is a Program. And a Program is that which Contains set of instructions, and an
Instruction contains Some Tokens. So Tokens are used for Writing the Programs the various Types of
Tokens those are contained by the Programs.
As in the English language, in a paragraph all the words, punctuation mark and the blank spaces are
called Tokens. Similarly in a C++ program all the C++ statements having Keywords, Identifiers,
Constants, Strings, Operators and the Special Symbols are called C++ Tokens. C++ Tokens are the
essential part of a C++ compiler and so are very useful in the C++ programming. A Token is an
individual entity of a C++ program.
DECLARATION OF A VARIABLE:-
A variable can hold the value that can be changed. The variables must be declare before they are
used in the program and the declaration of the variable can appear anywhere in the program in C++. This
makes the program much easier to write and reduce the error that may cause because of moving up and
down.
Syntax:- Data type variable name;
Ex:- 1. int m1,m2;
2.char sname(20);
Dynamic initialization of a variable:- One additional feature of C++ is that it permits the initialization
of a variables at runtime. This is referrred to as dynamic initialization. This means in C++ a variable can
be initialized at runtime.
Ex:- int tot = m1,m2,m3;
Both the declaration and initialization of variable can be done simultaneously
Reference Variable:- C++ introduces a new kind of a variable known as the reference variable. A
reference variable provides an alternative name ( alias name ) for the previously defined variable.
Syntax:- data type &reference name = variable name;
Ex:- int total= 100;
int &sum=total;
it represents that total is a integer type variable, sum is the alternative name declared to represent the
variable total. If we make the variable sum a reference to the variable total then sum and total can be used
interchangeable or alternatively to represent that variable. The statements cout<<total; and cout<< sum;
both print the value 100.
Expressions:- An expression is a combination of operators, constants, variables, arranged as per the rules
of the language to produce a value. It may also include function call which return value.
Expressions are of seven types:
1. Constant Expressions 5.Relational Expressions.
2.Integral Expressions 6.Logical Expressions.
3.Float Expressions 7.Bit wise Expressions
4.Pointer Expressions 8.Compound Expressions.
A combination of variables, constants and operators that represents a computation forms an expression.
Depending upon the type of operands involved in an expression or the result obtained after evaluating
expression, there are different categories of an expression. These categories of an expression are
discussed here.
• Constant expressions: The expressions that comprise only constant values are called constant
expressions. Some examples of constant expressions are 20, ‘ a‘ and 2/5+30 .
• Integral expressions: The expressions that produce an integer value as output after performing all types
of conversions are called integral expressions.
For example, x, 6*x-y and 10 +int (5.0) are integral expressions. Here, x and yare variables of type into
• Float expressions: The expressions that produce floating-point value as output after performing all
types of conversions are called float expressions.
For example, 9.25, x-y and 9+ float (7) are float expressions. Here, x 'and yare variables of type float.
• Relational or Boolean expressions: The expressions that produce a bool type value, that is, either true
or false are called relational or Boolean expressions.
• Logical expressions: The expressions that produce a bool type value after combining two or more
relational expressions are called logical expressions.
For example, x==5 &&m==5 and y>x I I m<=n are logical expressions.
• Bitwise expressions: The expressions which manipulate data at bit level are called bitwise expressions.
For example, a >> 4 and b<< 2 are bitwise expressions.
• Pointer expressions: The expressions that give address values as output are called pointer expressions.
For example, &x, ptr and -ptr are pointer expressions.
• Special assignment expressions: An expression can be categorized further depending upon the way the
values are assigned to the variables.
• Chained assignment: Chained assignment is an assignment expression in which the same value is
assigned to more than one variable, using a single statement. For example, consider these statements.
a = (b=20); or a=b=20;
In these statements, value 20 is assigned to variable b and then to variable a. Note that variables cannot be
initialized at the time of declaration using chained assignment. For example, consider these statements.
In this statement, the value 30 is assigned to variable b and then the result of (20+ 30) that is, 50 is
assigned to variable a. Note that the expression (b=30) is an embedded assignment.
In this statement, the operator += is a compound assignment operator, also known as short-hand
assignment operator.
Data types:- The kind of data that variables may hold in a programing language is called the datatype.
C++ offers a set of data types. They can be classified into the following three categories.
1.User defined data type
2.Built in data type
3.Derived data type
C++ datatypes
1.USER DEFINE DATATYPE:- Structure, Union and Class: Structure and union are the significant
features of C language. Structure and union provide a way to group similar or dissimilar data types
referred to by a single name. However, C++ has extended the concept of structure and union by
incorporating some new features in these data types to support object -oriented programming.
C++ offers a new user-defined data type known as class, which forms the basis of object-oriented
programming. A class acts as a template which defines the data and functions that are included in an
object of a class. Classes are declared using the keyword class. Once a class has been declared, its object
can be easily created. .
Enumeration type:- An enumerated datatype is a user defined data type which provides a way for
attaching names to numbers, there by increasing comprehensibility of the code. The “enum” keyword
automatically enumerates a list of words by assigning the values 0,1,2,----. This facility provides an
alternative, means for creating symbolic constants.
Ex:- enum shape { circle, square, triangle};
2.BUILT IN DATATYPE-
The basic (fundamental) data types provided by c++ are integral, floating point and void data type.
Among these data types, the integral and floating-point data types can be preceded by several type
modifiers.The various modifiers are short, long, signed and unsigned. By default the modifier is signed.
Integral Data Type: The integral data type is used to store integers and includes char (character) and int
(integer) data types.
Char: Characters refer to the alphabet, numbers and other characters (such as {, @, #, etc.) defined in the
ASCII character set. In C++, the char data type is also treated as an integer data type as the characters are
internally stored as integers that range in value from -128 to 127. The char data type occupies 1 byte of
memory (that is, it holds only one character at a time)
Int: Numbers without the fractional part represent integer data. In C++, the int data type is used to store
integers such as 4, 42, 5233, -32, -745. Thus, it cannot store numbers such as 4.28, -62.533. The various
integer data types with their size and range are listed in Table
Floating-point Data Type: A floating-point data type is used to store real numbers such as 3 .28, 64.
755765, 8.01, -24.53. This data type includes float and double' data types.
Void: The void data type is used for specifying an empty parameter list to a function and return type for a
function. When void is used to specify an empty parameter list, it indicates that a function does not take
any arguments and when it is used as a return type for a function, it indicates that a function does not
return any value..
3.DERIVED DATATYPES:- The three derived types in C++ are arrays functions,Pointers.
Arrays:- The application of arrays in C++ is a similar to that in C. The only exception is the way
character arrays are initialized. When initializing a character in C, the compiler will allow us to declare
the array size as the exact length of the string constant.
Ex: char str[3] = “xyz”;
It is assumed that the programmer intends to leave out the null character ie., “\o” in the definition . But
in C++ the size should be one longer than the number of characters in the string.
Ex: char str[4] =”xyz”;
Pointers:- Pointers are declared and initialized in C, C++ adds the concept of constant pointer to a
constant.
Ex: char * const ptr1 = “abc”;
OPERATORS IN C++
In addition to the operators like arithmetic operators, relational operators, logical operators, the
conditional operator and assignment operators that most of the languages support, C++ provides various
new operators that are given in Table
New operators
The scope resolution operator : : is a special operator that allows access to a global variable even though
the local variable has the same name. To understand the concept of scope resolution operator, consider
this example.
#include<iostream>
int x = 5;
int main ()
{ int x = 3;
return 0;
new and delete: C++ provides two dynamic allocation operators new and delete to allocate and
deallocates memory at run-time respectively. The new operator is a unary operator that allocates memory
and returns a pointer to the starting of the allocated space. The syntax of allocating memory using the new
operator is
where,
new=C++ keyword
For example
(or)
The life-time of a variable created at run-time using the new operator is not restricted till the execution of
the program. Rather, it remains in the memory until it is explicitly deleted using the delete operator.
When a dynamically allocated variable is no longer required, it must be destroyed using the delete
operator to ensure safe and efficient use of memory.
The syntax for using the delete operator is
delete p_var;
For example, to delete the pointers iptr and fptr of types int and float respectively, these statements are
used.
delete iptr;
delete fptr;
Manipulators:- Manipulators are operators that are used to format the data display. The most commonly
used manipulators are “end l” and “ setw( )”.
The end l manipulator, when used in a out put statement causes a line feed to be inserted. It has the
same of fact as using the newline character “\n”.
Ex: cout<<”m=” <<m << end l << “n=” << n<< end l;
Out put: m=5, n=6.
The manipulator setw( ) specifies a filed width for printing the value of the variable.
Example programe:
# include < iostream.h >
# include <iomanip.h >
main ( )
{
int basic= 950. Allowance = 95, total= 1045;
cout <<setw(10) << “Basic =” << setw(10) << basic <<end l
<< setw(10) <<”allowance =”<< setw(10) << allowance << end l
<<setw(10) <<”total =” <<setw(10) << total << end l;
}
FUNCTIONS IN C++
A function groups a number of programs statement into a unit and gives it a name. This unit can be
invoked other parts of the program. It is very difficult to implement a large problem. A complex problem
may be decomposed into a small and easily manageable parts or modules called functions. Functions are
very useful to read, write, debug and modify the complex problem. They can also easily incorporate in the
main program. In C++, the main( ) itself is a function. That means the main( ) is invoking the other
functions to perform various task. By using functions it is possible to reduce the size of program by
calling and using them at different places in a program.
The general form of a function definition is.
return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function prototype declaration and a function body. All the parts
of a function are -
Part Explanation
return_type is the type of data that function returns. It is not necessary that function will
Return Type
always return a value.
Function It is the actual name of the function. The function name and the parameter list together
Name forms the signature of the function
Parameters allow passing arguments to the function from the location where it is called
Parameters
from. Parameter list is separated by comma
Function
The function body contains a collection of statements that define what the function does.
Body
Example program:
# include < iostream.h >
void main( )
{
int x.y;
void output (int x, int y);
cout<<”This is our main program”;
output (x.y);
}
void output(int a, int b)
{
cout<<” Enter the value of a,b”;
cin>> a>>b;
int c= a+b;
cout<<c; }
Inline function:- Generally functions have memory space because all the calls to the function causes
same code to be executed. A function body need not be duplicated in memory space, it takes some extra
time.
To save execution time in short functions C++ provides a new feature called inline function.
An inline function is a function ie., expanded in line when it is invoke. That is the compiler replaces the
function call with the corresponding function cade. It is similar to macros in C. But the main drawback
with the macros is that they are not really functions and therefore, the usual error checking doesnot occur
during compilation. The inline functions are defined as follows.
Syntax:- inline function header
{
function body;
}
Ex: inline float mul(p,q)
{
return (p,q);
}
The inline function must be specified with a key word “inline”.
RULES:
1.Inline functions should be defined before main program.
2.The reserve word “inline” should appear in the function heading.
3.Inline function should be small because the speed benefits of inline function diminish as the function
grows in size.
4.The inline function should not contain control structure of loop structures.
5.The inline function does not work for recursive statements.
Example program:-
# include <iostream.h>
inline float mul(float p,float q)
{
return (p*q);
}
inline int div(int x, int y)
{
return (x/y)
}
Void main()
{
float p=3,q=4.8;
int x=6,y=3;
cout <<”Multiplication of 2 numbers” << mul(p,q);
cout <<”Division of 2 numbers” << div(x,y);
getch( );
}
Default arguments:- In C++ programming, you can provide default values for function parameters. The
idea behind default argument is very simple. If a function is called by passing argument/s, those
arguments are used by the function. But if all argument/s are not passed while invoking a function then,
the default value passed to arguments are used.
Note :- In default arguments the trailing arguments can have defined values and therefore we must add
from right to left. We cannot provide a default value to a particular argument in the middle of an
argument list.
Ex:- float amount (int p, int t=7, float r=0.15); ||legal.
float amount (int p, int t=7, float r); || illegal.
Advantages:-
1.We can use default arguments to add new parameters to the existing function.
2.Default arguments can be used to combine similar function into one.
Example program:-
# include <iostream.h>
void main( )
{
float amount (int p=5000, int t=7, float r=0.15);
float value1, value2,value3;
cout <<”value 1=” <<amount ( ) <<end l;
cout <<”value 2=” <<amount ( 3000,1) <<end l;
cout <<”value 3=” <<amount (6000,3,0.15) <<end l;
}
float amount (int p, int t,float r)
{
float si;
si+ (p*t*r)/100;
return (si);
}
FUNCTION OVERLOADING:- Over loading refer to the use of same thing for different purposes. C++
also permits over loading of functions. This means we can use the same function name to create functions
that perform a variety of different task. This is known as function overloading or function polymorphism
in Oop.
By using the concept of function overloading we can design a family of functions with same function
name but with different argument list. Function would perform different operations depending on the
argument list in the function call.
/* Example of function overloading */
int test() { }
int test(int a){ }
int test(double a){ }
int test(int a, double b){ }
All 4 functions mentioned above are overloaded function. It should be noticed that, the return type of all 4
functions is same,i.e, int. Overloaded function may or may not have different return type but it should
have different argument(either type of argument or numbers of argument passed
Example program:-
/*Calling overloaded function test() with different argument/s.*/
#include <iostream>
using namespace std;
void test(int);
void test(float);
void test(int, float);
int main() {
int a = 5;
float b = 5.5;
test(a);
test(b);
test(a, b);
return 0;
}
Output
Integer number: 5
Float number: 5.5
Integer number: 5 And float number: 5.5
CALL BY REFERENCE:- Provision of reference variables in C++ permits us to pass parameters to the
function by reference. When we pass arguments by reference, the formal arguments in the called function
become alias to the arguments in the calling function. This means that when the function is working with
its own arguments, it is actually working on the original data.
Example program:-
# include <iostream.h>
void swap ( int *x, int *y);
void main( )
{
int a,b;
cout <<”Enter a,b values”;
cin>>a>>b;
swap (&a, &b);
getch( );
}
Void swap(int *x, int *y)
{
Int t;
t= *x;
*x= *y;
*y= t;
cout<<”a=”<<*x;
cout<<”b=”<<*y;
}
CLASS AND THE OBJECTS
The most important feature of C++ is the “class”. A class is an extension of the idea of structure used
in C.
C++ supports all the features of structure as defined in C. But C++ has expanded its capabilities
further to satisfy its Oop philosophy. It attempts to bring the user defined types as close as possible to the
built in types and also provides a facilities to hide the data which is one of the main principal of Oops.
A class is the collection of related data and function under a single name. A C++ program can have
any number of classes. When related data and functions are kept under a class, it helps to visualize the
complex problem efficiently and effectively
When we define a class, we define a blueprint for a data type. This doesn't actually define any data, but it
does define what the class name means, that is, what an object of the class will consist of and what
operations can be performed on such an object
When a class is defined, no memory is allocated. You can imagine like a datatype.
int var;
The above code specifies var is a variable of type integer; int is used for specifying variable var is of
integer type. Similarly, class are also just the specification for objects and object bears the property of that
class.
Defining the Class in C++
Class is defined in C++ programming using keyword class followed by identifier(name of class). Body of
class is defined inside curly brackets an terminated by semicolon at the end in similar way as structure.
A class is a way to bind the data and it associated function together .It allows the data to be hidden if
necessary from external use. When defining a class we are creating a new abstract data type that can be
created as any other built in type. Generally a class specification has
1. Class declaration.
2. Function definition.
Class declaration describes the dypes and scope of its members.
The class function definitions describes how the class functions are implemented the general form of class
definition is.
Syntax:
Class < class name>
{
Private:
Variable declaration;
Function declaration;
Public:
Variable declaration;
Function declaration;
};
The members that have been declared as private can be accessed only from within the class.
On the other hand public members can be accessed from outside the class also. The data hiding using the
private declaration is the key feature of object oriented programming. The use of key word private is
optional. If both the labels (key word ) are missing then by default, all the members are private. A class is
completely hidden from the outside world .Functions with in the class are known as “member functions”
Only the member functions can have access to the private data members .
Example:- class item
{
private :
int num;
float price;
public:
void get data ( );
void put data( );
};
In this example the class name is item. This name now become a new type identifier that can be used to
declare instance or objects of that class type. Item contains two data members and two member functions.
The data members are private and member functions are public .
Creating objects:-
Once a class have been declared we can create the variables of that type using the class name for
example:
item x;
it creates a variable ‘x’ of type item. In C++ the class variables are known as objects.
Accessing class members:-
The private data of a class can be accessed only through the member functions of that
class .The main( ) function cannot contain statement “num” and “price” directly.The following is the
format for calling a member function.
Syntax:- object name . function name ( Argument list );
Ex: - x.getdata ( int num, float price );
x getdata ( 100, 25.3 );
The above function call statement assigns the value of 100 to num and 25.3 to price.
Defining member function:-
Members function can be defined in two places.
1. Outside the class definition.
2. Inside the class definition.
1.out side the class definition:-
Members functions that are declared inside a class have to be defined separately outside the class. These
definitions are very much like to the normal functions. They should have a function header and function
body.. An important difference between member function and a normal function is member function
incorporates a member ship identification label in the header. This label tells the compiler to which class
the function belongs .The general form of a member function definition is.
Syntax: return type class name :: function_name ( Argument list )
{
function body;
}
Explanation:-
The member ship label “class name” tells the compiler that the function name belongs to
the particular class. The symbol “ :: “ is called “scope resolution operator”.
Member function can access the private data of a class. A member function can call
another member functions directly without using a dot operator.
Ex:- write a program to display the room details of a hotel defining the member functions outside the
class.
# include < iostream.h >
class hotel
{
Private:
int rno, rrent;
char cname [20];
char rtype[10];
Public :
void getdata( );
void display( );
};
void hotel :: get data( )
{
cout <<”enter customer name, room type, room number, room rent” <<end l;
cin >> c name >> r type >> r no >>r rent;
}
void hotel :: display ( ){
cout << “\n customer name is “ << c name << end l;
cout << ”\n Room type is “ << r type << end l;
cout << ”\m Room number is” << r no << end l;
cout << “\n Room rent is” << r rent << end l;
}
void main ( )
{
clrscr ( );
hotel h1,h2;
h1 getdata( );
h1 display( );
h2 getdata( );
h2 display( ); getch();
2. Inside the class definition;- Another method of definition a member function is to replace the
function declaration by the function definition inside the class.
Syntax: class < class. name >
{
Public:
function name ( argument list )
{
function body;
}
When a function is defined inside a class it is treated as “inline function”. Therefore all the restrictions
and limitations that a applicable to an in line function are also applicable here.
Ex:- W.A.P to display the name of the person and his date of birth.
# include < iostream.h >
class dob
{
private:
char name[20];
int date,month, year;
public:
void get data( )
{
cout << “\n enter name, date, month, year”;
cin >> name >> date >> month year;
}
void display( )
{
cout << “\n person name is “ << name << end l;
cout << “\n date of birth is “ << date << “_” << month << “_” << year;
}
};
Void main()
{
clrscr( );
dob p;
p.get data( );
p.display( );
getch( ); }
Nesting of member function:-
The member functions can be called by using its name inside other member functions of the same
class. This is known as nesting of member functions.
Example:- W.A.P to find the largest of two numbers
# include < iostream.h >
# incluce < conio.h >
class big
{
private:
int a,b;
public:
void getdata( );
void display( );
int largest( );
};
void big :: getdata( )
{
cout << “Enter values for a and b “ << end l;
cin >> a >>b;
}
void big :: display( )
{
cout << “ Largest value is “ << largest( );
}
int big :: largest ( )
{
if ( a>b)
return ( a );
else
return ( b )
}
main ( )
{
clrscr( );
big b;
b.getdata( );
b. display( ); getch( ); }
STRINGS AND ARRAYS
Arrays with in class:-
The arrays can used as member variables in a class .The following definition is valid.
Ex:- const int size = 50;
class item
{
int a[size];
public:
void input( );
void display ( );
};
The array variable ‘a’ is declared as a private member of the class item. This can be used in the member
functions like any other variables.
W.A.P to generate the grade of a student by calculating the avg .
# include < iostream.h >
# include < conio.h >
class student
{
int sno, tot, m[10], n;
char sname[25], grade[15];
float avg;
public:
void getdata( );
void cal( );
void grade( );
};
void student :: getdata( )
{
cout << “in enter sno,sname”;
cin>> sno >> sname;
cout <<”\n Enter how many subjects marks u Want”;
cin>>n;
for ( int i=0; i<n; i++ )
{
cout << “\n enter marks “;
cin >> m[i];
}
}
void student :: cal( )
{
int i,tot =0;
for ( i=0; i<n; i++ )
{
tot = tot +m[i];
}
cout <<”\n total =” <<tot;
avg =tot\n;
cout <<”\n average =” <<avg;
}
void student :: grade( )
{
if ( ( avg >80) && (avg<100) )
{
strcpy (grade,”Dist”);
}
else if ( (avg >60) && (avg <80) )
{
strcpy (grade ,”First”);
}
else if ( ( avg >45) && (avg<60) )
{
strcpy (second, “Second”);
}
else if ( ( avg > 35) && (avg < 45) )
{
strcpy (grade, “Third”);
}
else
{
strcpy (grade, “Fail”);
}
cout <<”\n Grade =” << grade;
}
void main( )
{
student s;
s.get data( );
s.cal( );
s.grade( );
getch( );
}
Array of object:-
An array can be of any datatype including the structure. Similarly we can also have arrays of variables
that are of type class. Such variables are called “Array” of objects.
Syntax:- class < class_name >
{
private :
data members;
mamber functions;
public:
data members;
members functions;
}
class_name object_name[size];
where ‘size’ is a user defined size of the array of the class object. Since an array of object behaves like
any other array, we can use the usual array accessing members. We access the individual elements
through the dot operator to access the member function.
Example:-W.A.P. to calculate the net salary for different employees.
# include < iostream.h >
class emp
{
int eno,da, hra,ba, net sal;
char ename[15];
public:
void getdata ( );
void cal( );
void disp( );
};
void emp :: getdata( )
{
cout <<”Enter eno, ename,ba,hra,da” <<end l;
cin >> eno>> ename>> ba>> hra>> da;
}
void emp :: cal( )
{
net sal = da+hra+ba;
}
void disp ::disp()
{
cout <<”eno=” << eno<< end l << “ename=” << ename << end l << “net salary =” <<net sal;
}
void main( )
{
emp e[20];
int n,i;
cout <<”\n enter how many employees do U want”;
cin >> n;
for ( i=1; i<=n; i++ )
{
e[i]. getdata( );
e[i]. cal( );
e[i]. disp( );
}
}
STATIC DATA MEMBERS:
We can define class members static using static keyword. When we declare a member of a class as
static it means no matter how many objects of the class are created, there is only one copy of the static
member.
A static member variable has certain special characteristics. They are.
1.It is initialized to zero. When the first object of its class is created. No other initialization is permitted.
2. Only one copy of that member is created for the entire class and is shared by all the objects of that class
no matter how many objects are created.
3. It is a visible only with in the class, but its life time is in the entire program.
4. The static variable created inside the class. It should be defined outside the class by using the class
name and scope resolution operator.
Syntax:
class class_ name
{
private:
static variable declaration;
variable declaration;
public:
variable declaration;
member function declaration;
}
Return type class name :: static variable name;
The type and scope of each static member variable must be defined outside the class definition.
This is necessary because the static date member is stored separately rather than as a part of an object;
Static variable are also known as class variables. Because they are associated with the class rather
than any object.
Example:-W.A.P. to illustrate the use of static data member.
#include<iostream.h>
#include<conio.h>
class stat
{
int code;
static int count;
public:
stat()
{
code=++count;
}
void showcode()
{
cout<<"\n\tObject number is :"<<code;
}
static void showcount()
{
cout<<"\n\tCount Objects :"<<count;
}
};
int stat::count;
void main()
{
clrscr();
stat obj1,obj2;
obj1.showcount();
obj1.showcode();
obj2.showcount();
obj2.showcode();
getch();
}
Output:
Count Objects: 2
Object Number is: 1
Count Objects: 2
Object Number is: 2
Static member function:-
By declaring a function member as static, you make it independent of any particular object of the class. A
static member function can be called even if no objects of the class exist and the static functions are
accessed using only the class name and the scope resolution operator ::.
A member function ie; declared using the key word “static” will become static member function. A static
member function has the following properties.
1.A static member function can be have access to only other static member functions (or) variables
declared in the same class.
2. The static member function can be called using the class name as follows.
Syntax: class name :: function name( );
Example:- W.A.P to illustrate the use of static member function
#include<iostream.h>
#include<conio.h>
class test
{
int code;
static int count;
public :
void setcode(void)
{
code= ++count;
}
void showcode(void)
{
cout<<"object number"<<code<<endl;
}
static void showcount(void)
{
cout<<"count"<<count<<endl;
}
};
int test::count;
int main()
{
clrscr();
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
getch();
return(1);
}
OUTPUT
Count 2
Count 3
Object number 1
Object number 2
Object number 3
Friend function:-
One of the important concept of OOP is data hiding, i.e., a nonmember function cannot access an object's
private or protected data. But, sometimes this restriction may force programmer to write long and
complex codes. So, there is mechanism built in C++ programming to access private or protected data
from non-member function which is friend function and friend class.
If a function is defined as a friend function then, the private and protected data of class can be accessed
from that function. The complier knows a given function is a friend function by its keyword friend. The
declaration of friend function should be made inside the body of class (can be anywhere inside class
either in private or public section) starting with keyword friend.
1.It is not in the scope of the class to which it has been declared as a friend.
2.Since it is not in the scope of the class, it cannot be called using the object of that class.
3. It can be invoke like a normal function without the help of any object.
4. Unlike member function, it cannot access the member variables directly, and as such it has to use an
object name and dot operator with each member variable.
5. It can be declared either in public or the Private part of the class.
6.The function definition cannot have the key word friend or the scope resolution operator ( :: ).
7. The friend function has objects as the function arguments.
The syntax for the friend function is
Syntax: Friend return type function name (argumentlist).
W.A.P. to calculate the mean of 2 numbers using friend function.
#include < iostream.h >
#include < conio.h >
class sample
{
int a,b;
Public:
Void get data( )
{
Cout <<” \n Enter a and b values”;
Cin>> a>> b;
}
Friend int mean ( sample s);
};
int mean ( sample s)
{
return (s.a+s.b)/2;
}
void main ( )
{
sample s;
clrscr( );
s.getdata( );
cout <<”mean=” << mean( s )<< end l;
getch( );
}
Member functions of one class can be friend of another class. In such cases they are defend using the
scope resolution operator as shown bellow.
Class x
{
--------
-------
int fun1( );
-------
-------
};
Class y
{
-------
-------
friend int x:: fun1( );
------
------
};
We can also declare all the member function of one class as the friend frnction of another class. In
such cases the class is called “friend class”.
Class x
{
------
------
Public:
Data member;
Member function;
------
------
};
Class y
{
-------
-------
friend class x;
-------
-------
};
Parameterized constructor:- The constructor integer ( ), defined above initializes the data member of
the object to zero. However, it may be necessary to initialize the various data elements of different objects
with different values when they are created. C++ permits us to achieve this by passing arguments to the
constructor function when the objects are created. The constructors that can takes arguments are called”
Parameterized Constructors”. The parameterized constructor can be defined as follows.
class integer
{
int m,n;
Public:
integer ( int x, int y )
{
m=x;
n=y;
}
};
( or )
class integer
{
int m,n;
Public:
integer ( int n, int y ); // constructor declared
};
integer :: integer ( int x, int y ) // constructor defined
{
m=x;
n=y;
}
When a constructor has been parameterized the object declaration statement such as integer num1 may
not work. We must pass the initial values as arguments to the constructor function, when an object is
declared,
1.By calling the constructor explicitly.
2.By calling the constructor implicitly.
The following declaration illustrates the first method.
integer num1= integer (0,50);
This method creates an integer object num1 and passes the values 0 and 50 to it.
W.A.P. to input product no, pname, no.of product sold, cost of each product. Calculate the bill
amount based on the discount 10% if bill amount =1000, otherwise no discount. Print bill amount .
#include < iostream.h>
#include < conio.h>
class product
{
char pname[15];
int pno,nps,cp.bamt;
float disc,nba;
public:
product ( )
{
disc=0;
}
void getdata( )
{
cout <<”enter product no, product name , no.of product sold, cost of each product”;
cin >> pno >> pname >> nps >>cp;
}
void cal( )
{
b amt= nps x cp;
if (bamt>= 1000)
{
disc =0.1 * b amt;
nba = bamt- disc;
cout <<” Net bill amount=” << nba;
}
else
{
cout <<”bamt =”<< bamt<<”\n no dis count “ << end l;
}
};
void main( )
{
product p1;
clrscr( );
p1.getdata( );
p1.cal( );
getch( );
}
Copy constructor:- The copy constructor is used to declare an initialize an object from another object.
The process of initializing through a copy constructor is called “Copy initializing”. A copy constructor
takes a reference to an object of the same class as itself as an argument.
Syntax
Eg:
#include < iostream.h>
#include < conio.h>
class node
{
int id;
public:
code( )
{
}
code (int a)
{
id =a;
}
code ( code & x)
{
id=x.id;
}
void display( )
{
cout << id;
}
};
void main( )
{
code a(100); // object A is created or initialsed
code b(a); // copy constructor called
cout <<”id of A is “;
a.display ( );
cout <<” \n id of B is “;
b.display( );
}
Note:- A reference variable has been used as an object to the copy constructor. We cannot pass the
arguments by value to a copy constructor.
Multiple constructor in a class:- We can declare different types of constructors in a class.
Ex:-
#include < iostream.h>
#include <conio.h>
class integer
{
int m,n;
public:
void display( );
integer( )
{
m=0, n=0;
}
integer ( int x, int y)
{
m=x; n=y;
}
integer (integer & i)
{
m=i.m;
n=i.n;
}
};
void main( )
{
integer i1;
i1.display( );
integer i2(100,200);
integer i3(i2);
i2.display( );
i3.display( );
}
In the first case the constructor itself supplies the data value and vo values are passed by the calling
program. In the second case the function call passes the appropriate values from main function. This
declares three constructors for a integer object. The first constructor receives no argument. For example
the declaration integer i1 would automatically invok the first constructor and set both m an n of i1 to zero.
The statement integer i2 (100,200) ; would call the second constructor which will initialize the data
members m and n of i2 to 100 & 200 representively. Finally the statement integer i3(i2); would invoke
the third constructor which copies the values of i2 into i3.
Dynamic initialization of objects:-
Class objects can be initialized dynamically to i.e; initial value of an object may be provided during
runtime. One advantage of dynamic initialization is that we provide the memory space for the object at
runtime. If we pass the values to the objects at the runtime then we call it as a dynamic initialization of
object.
A program for dynamic initialization of object:-
#include < iostream.h>
#include< conio.h>
class integer
{
int m,n;
public:
integer (int b, int v)
{
m=b; n=v;
}
void display( )
{
cout <<”m=” <<m<<end l;
cout <<”n=” <<n<< end l;
}
};
void main( )
{
int b,v;
cout<< “enter b and v values”;
cin >> b>>v;
integer i1 (b,v); // inplicity
i1.display( );
vout<<”enter b & v values”;
vin >>b >>v;
integer i2= integer (b,v);
i2.display( );
}
Destructors:- A Destructor is used to destroy the objects that have been created by constructor. Like a
constructor the destructor is a member function whose name is same as the class name. But it is produced
by tilde(~). For example the destructor for the class integer can be defined as
~ integer( )
{
}
A destructor neither takes any arguments nor does it return any value. It will be invoked directly by the
compiler upon that is no longer accessible. It is a good practice to declare destructors in a program since it
releases memory space for future use.
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
private:
double length;
};
return 0;
}
When the above code is compiled and executed, it produces the following result:
6. OPERATOR OVERLOADING
Operator overloading is one of the many existing features of C++ language. It is an important technique
that has enhance the power of extendibility of C++. We know that C++ tries to make the user defined data
type behave as close as possible to the built in types.
The meaning of operators are already defined and fixed for basic types like: int, float, double etc in C++
language. For example: If you want to add two integers then, + operator is used. But, for user-defined
types(like: objects), you can define the meaning of operator, i.e, you can redefine the way that operator
works. For example: If there are two objects of a class that contain string as its data member, you can use
+ operator to concatenate two strings. Suppose, instead of strings if that class contains integer data
member, then you can use + operator to add integers. This feature in C++ programming that allows
programmer to redefine the meaning of operator when they operate on class objects is known as operator
overloading.
You can write any C++ program without the knowledge of operator overloading. But, operator operating
are profoundly used by programmer to make a program clearer. For example: you can replace the code
like: calculation = add(mult(a,b),div(a,b)); with calculation = a*b+a/b; which is more readable and easy to
understand.
The return type comes first which is followed by keyword operator, followed by operator sign,i.e., the
operator you want to overload like: +, <, ++ etc. and finally the arguments is passed. Then, inside the
body of you want perform the task you want when this operator function is called.
This operator function is called when, the operator(sign) operates on the object of that class class_name.
7.Unary operator overloaded by means of a member function, takes no explicit arguments and return no
explicit value but those overloaded by means of a friend function take one reference argument.
8.Binary operators overloaded through a member function take one explicit arguments and those which
are overloaded through a friend function take two explicit argument.
9.When using binary operators which are overloaded through a member function, the left hand operator
must be an object of relevant class.
10.Binary arithmetic operators such as +, -, * , /, \, must explicitly return a value. They must not attempe
to change their own arguments.
W.A.P. to overload binary operator ‘+’ using member function.
#include <iostream>
#include <conio.h>
using namespace std;
class Complex
{
int real,img;
public:
Complex() //default constructor
{
real=0;
img=0;
}
Complex(int r,int ig) //Parametrized constructor
{
real=r;
img=ig;
}
Complex operator + (Complex &c) //Memory consumption is minimised by the use of &
{ //Class name as the derived type
Complex t;
t.real=real+c.real;
t.img=img+c.img;
return t;
}
void show()
{
cout<<real<<"+i"<<img<<endl;
}
};
int main()
{
Complex c1(5,2),c2(7,3),c3;
c1.show();
c2.show();
c3=c1+c2;//need a default constructor to initialize the values for c3
c3.show();
getch();
}
We should not to the following features of this operator +( ).
1.It receives only one complex type argument explicitly.
2.It returns a complete type value.
3.It is a member function of class complex.
Here the function is expected and to add two complex values and returns a complex values as the
result. But receives only one value as arguments.
Here the statement c3=c1+c2 will invoke this function. We know that a member function can be
invoke only by an object of the same class. Here the object c1 takes the responsibility of invoking th
function and c2 places the role of an argument that is calls to the function. The above invocation
statement is equivalent to c3= c1. Operator +( c2 );
In the operator +( ) function the data members of c1 can accessed directly and the data members of
c2 using dot operator.
W.A.P to overload unary ‘++’ using member function
#include<iostream.h>
#include<conio.h>
class complex
{
int a,b,c;
public:
complex(){}
void getvalue()
{
cout<<"Enter the Two Numbers:";
cin>>a>>b;
}
void operator++()
{
a=++a;
b=++b;
}
void operator--()
{
a=--a;
b=--b;
}
void display()
{
cout<<a<<"+\t"<<b<<"i"<<endl;
}
};
void main()
{
clrscr();
complex obj;
obj.getvalue();
obj++;
cout<<"Increment Complex Number\n";
obj.display();
obj--;
cout<<"Decrement Complex Number\n";
obj.display();
getch();
}
2.Multilevel inheritance:- The mechanism of deriving a class from another derived class is known as
Multilevel inheritance.
A Base class
B Deieved class
C Derived class
3.Multiple inheritance:- If a class inherit peoperties from more than one class or from more than one
level is called Multiple inheritance.
Base class A B Base class
C Derived class.
4.Hierarchical inheritance:- If the properties of one class may be inherited by more than one derived
class is known as hierarchical inheritance.
A Base class
B C D
Derived class.
5.Hybrid inheritance:- It is the combination of multiple and multilevel inheritance.
Defining a derived class:-A derived class cab be defined by spefiying its relation with the base class in
addition to its own details.The general form of defining a derived class is
Syntax:-class derived class name: visibility mode base class name
{
Members of derived class
};
The colon indicates that the derived class is derived from the base classname.Visiblity mode is optional
and if present may be either private or public.The default visibility mode is private
The visibility mode specifies whether the features of base class or privately derived or publicly derived.
Eg:-
class ABC: private XYZ //private derivation
{
members of ABC
};
class ABC: public XYZ //public derivation
{
members of ABC
};
class ABC: XYZ //private derivation by default
{
member of ABC
};
Member How Members of the Base Class Appear in the Derived Class
Access
Specifier
Private Private members of the base class are inaccessible to the derived
class.
Protected members of the base class become private members of
the derived class.
Public members of the base class become private members of the
derived class.
Protected Private members of the base class are inaccessible to the derived
class.
Protected members of the base class become protected members of
the derived class.
Public members of the base class become protected members of the
derived class.
Public Private members of the base class are inaccessible to the derived
class.
Protected members of the base class become protected members of
the derived class.
Public members of the base class become public members of the
derived class.
Single inheritance
W.A.P to illustrate e single inheritance by plaicing the visibility mode public in the derived class.
class Shape
{
protected:
float width, height;
public:
void set_data (float a, float b)
{
width = a;
height = b;
}
};
int main ()
{
Rectangle rect;
Triangle tri;
rect.set_data (5,3);
tri.set_data (2,5);
cout << rect.area() << endl;
cout << tri.area() << endl;
return 0;
}
Making a private member inherited:- We know that private member of a base class cannot be inherited
and is not available for the derived class directly. Suppose if we change the private member to public, this
would make accessible to all the other functions of the program. This would take away tha advantage of
data hiding.
C++ provides a third visibility modifier, protected which serve a limit purpose in inheritance.
A member declared as protected is accessible by the member function within its class and any class
immediately derived from it . It cannot be accessed by the functions outside theirs two classes.
When a protected member is inherited in public mode it becomes protected to the derived class and
therefore is accessible by the member functions of the derived class. It is also ready for future inheritance
.
A protected member inherited in private mode, becomes private in the derived class. Although it is
available to the member functions of the derived class, it is not available for further inheritance (since
private members cannot be inherited).
It is also possible to inherit a base class in protected mode. In protected derivation, both public and
protected members of the base class become protected members to the derived class.
The keywords private, protected, public may appear in any order and any no.of times in the declaration
of the class. For example.
Class data
{
Protected:
--------
--------
public:
--------
--------
private:
--------
---------
public:
--------
---------
};
The table for the visibility of inherited members.
Base class derived cass visibility
Visibility public private protected
Derivation derivation derivation
Private not inherited not inherited not inherited
Public public private proteccted
Protected protected private protected
Multilevel inheritance:- It is non-uncommon (common) that a class is derived from another derived
class . The class A serves as a base class for the derived class B, which in term serves as a base class for
the derived class C. The class B is known as “Intremediate base class”, since it provides a link between A
and C. The chain ABC is known as Inheritance path.
Base path
A
Let us consider a simple example. Assume the test result of a batch of students are stored in three
different classes class student stores the roll.no, class test stores the marks obtained in 2 subjects and class
result contains the total marks obtaimed in the test. The class result can inhert the details of marks
multilevel inheritance. The class result after inheritance would contain following members.
Program for multilevel inheritance.
#include < iostream.h>
#include< conio.h>
class student
{
protected : int roting;
Public : void get no( )
{
cout<< “\n enter your rollno”;
cin >> rollno:
}
cout<<”\n Roll no=” << roll no;
};
class test : public student
{
protected : int sub1; sub2;
public : void getmarks( )
{
cout<< “\n enter 2 subjects merks”;
cin >> sub1 >> sub2;
}
void putmarks( )
{
cout<< “\n marks 1 =” << sub1;
cout << “\n marks 2 =” << sub2;
}
};
class result : public test
{
private : int total;
public : void display( )
{
putno( );
putmarks( );
total= sub 1=sub 2;
cout<< “\n Total=” << total;
}
};
void main( )
{
result s;
clrscr( );
s.getno( );
s.getmarks( );
s.display( ); }
Multiple inheritance:- A class can inherit the attributes of two or more classes, is known as multiple
inheritance. Multiple inheritance allows us to combine the features of several existing classes as a
starting point for defining new classes. It is like a child inheriting the physical features of one parent and
the intelligence of another. It is represented as follows.
B1 B2 B3
C
----
class student
{
protected:
int rno,m1,m2;
public:
void get()
{
cout<<"Enter the Roll no :";
cin>>rno;
cout<<"Enter the two marks :";
cin>>m1>>m2;
}
};
class sports
{
protected:
int sm; // sm = Sports mark
public:
void getsm()
{
cout<<"\nEnter the sports mark :";
cin>>sm;
}
};
class statement:public student,public sports
{
int tot,avg;
public:
void display()
{
tot=(m1+m2+sm);
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal : "<<tot;
cout<<"\n\tAverage : "<<avg;
}
};
void main()
{
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();
}
Output:
90
80
Hierarchical inheritance:-
If the traits of one class may be inherited by more than one derived class is known as Hierarchical
inheritance .
Eg:- W.A.P. to show the vehicle database using Hierarchical inheritance.
The hierarchical inheritance for vehicle database is represented as.
Vehicle
car truck
Here the base class is vehicle , car and tuck are derived classes. They inherits the properties of the
vehicle.
Exsample Program:- In the Below program Class A is Base Class and Class B ,Class C ,Class D are
derived class.(As Per above Diagram)
#include<iostream.h>
#include<conio.h>
};
int main()
{
clrscr();
Example programme: In the below program class B inherits property(member function) of class A
which is base class and class D inherits property
from class B and class
#include<iostream.h>
#include<conio.h>
class C
{
public:
int h;
void height()
{
cout<<"\n\nHeight :::\t";
cin>>h; //Height is enter by user
}
};
int main()
{
clrscr();
D d1;
d1.result();
getch();
Virtual Base class:- Consider a situation where all the three kinds of inheritance namely multilevel,
multiple and hierarchical inheritance are involved. This is illustrated as.
students
test sports
result
It shows that the result class has two direct base classes test and sports which
themselves have a common base class student. The result inherits the traits (properties) if students
via(though) of two separate line. The student class is sometimes referred as indirect base class.
Inheritance by the class result might pose some problems. All the public and protected members of
student class are inherited into result class thrice, first via test class and again via sports class. this means,
the result class would have duplicate sets of members inherited from base class student. This introduces
ambiguity and should be avoided.
The duplication of inherited members gave to their multiple path can be avoided by making the common
base class as “virtual base class”.
When a class is made a virtual base class C++ takes necessary care to see that only one copy of that class
is inherited, regard less of how many inheritance pass exist between virtual base class and a derived base
class.
Syntax:- class base class name
{
----
------
class deprival class name : visibility mode virtual Base class name.
{
------
------
};
The student class is considered as a virtual base and it is represented as follow.
students
test sports
result
#include <iostream.h>
class student
{
proteced : int r no;
public : void get no( )
{
cout <<\n enter your roll no”;
cin >> r no;
}
void put no( )
{
cout <<” roll number =” << r no;
}
};
class test : public virtual student
{
protected : int m1, m2, m3;
public : void get marks( );
{
cout<< “\n enter marks of 3 subjects”;
cin >> m1 >> m2 >> m3;
}
void putmarks( )
{
cout <<” maths = “<< m1;
cout <<” physics =” << m2;
cout <<” computers =” << m3;
}
};
class sports : public virtual student
{
protected : int score;
public : void getscore( )
{
cout<< “ enter the sports weightage”;
cin >> score;
}
void putsscore( )
{
cout <<” score =” << score;
}
};
class result : public test, public sports
{
private : int tot;
public : void getresult( )
{
putno( );
putmarks( );
putscore( );
tot = m1+ m2+m3+score;
cout <<” Total=” <<tot;
}
};
void main( )
{
result s;
clrscr( );
s.get no( );
s.getmarks( );
s.getscore( );
s.getresult( );
getch( );
}
C++ Pointers
ointers are the powerful feature of C++ programming which differs it from other popular programming
languages like: Java, Visual Basic etc.
To understand pointers, you should have the knowledge of address in computer memory. Computer
memory is broken down into bytes and each byte has its own address. For example: In 1KB memory,
there are 1024 bytes and each byte is given an address (0 - 1023).
Pointers Variables
Consider a normal variable as in above example, these variables holds data. But pointer variables or
simply pointers are the special types of variable that holds memory address instead of data.
The statement above defines a pointer variable p. The pointer p holds the memory address. The asterisk is
a dereference operator which means pointer to. Here pointer p is a pointer to int, that is, it is pointing an
integer.
Note: In above statement p is a pointer variable that holds address not *p. The *pis an expression. The
content(value) of the memory address pointer p holds is given by expression *p.
Example 2: C++ Pointers
#include <iostream>
using namespace std;
int main() {
int *pc, c;
c = 5;
cout<< "Address of c (&c): " << &c << endl;
cout<< "Value of c (c): " << c << endl << endl;
c = 11; // The content inside memory address &c is changed from 5 to 11.
cout << "Address pointer pc holds (pc): " << pc << endl;
cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;
*pc = 2;
cout<< "Address of c (&c): "<< &c <<endl;
cout<<"Value of c (c): "<< c<<endl<< endl;
return 0;
}
Output
int main() {
float a[5];
float *ptr;
return 0;
}
If there are member functions with same name in base class and derived class, virtual functions gives
programmer capability to call member function of different class by a same function call depending upon
different context. This feature in C++ programming is known as polymorphism which is one of the
important feature of OOP.
If a base class and derived class has same function and if you write code to access that function using
pointer of base class then, the function in the base class is executed even if, the object of derived class is
referenced with that pointer variable. This can be demonstrated by an example.
#include <iostream>
using namespace std;
class B
{
public:
void display()
{ cout<<"Content of base class.\n"; }
};
class D : public B
{
public:
void display()
{ cout<<"Content of derived class.\n"; }
};
int main()
{
B *b;
D d;
b->display();
Note: An object(either normal or pointer) of derived class is type compatible with pointer to base class.
So, b = &d; is allowed in above program.
Output
In above program, even if the object of derived class d is put in pointer to base class, display( ) of the
base class is executed( member function of the class that matches the type of pointer ).
Virtual Functions
If you want to execute the member function of derived class then, you can declare display( ) in the
base class virtual which makes that function existing in appearance only but, you can't call that function.
In order to make a function virtual, you have to add keyword virtual in front of a function.
#include <iostream>
using namespace std;
class B
{
public:
virtual void display() /* Virtual function */
{ cout<<"Content of base class.\n"; }
};
class D1 : public B
{
public:
void display()
{ cout<<"Content of first derived class.\n"; }
};
class D2 : public B
{
public:
void display()
{ cout<<"Content of second derived class.\n"; }
};
int main()
{
B *b;
D1 d1;
D2 d2;
/* b->display(); // You cannot use this code here because the function of base class is virtual. */
b = &d1;
b->display(); /* calls display() of class derived D1 */
b = &d2;
b->display(); /* calls display() of class derived D2 */
return 0;
}
Output
After the function of base class is made virtual, code b->display( ) will call the display( ) of the
derived class depending upon the content of pointer.
In this program, display( ) function of two different classes are called with same code which is one of
the example of polymorphism in C++ programming using virtual functions.
In C++ programming, sometimes inheritance is used only for the better visualization of data and you do
not need to create any object of base class. For example: If you want to calculate area of different objects
like: circle and square then, you can inherit these classes from a shape because it helps to visualize the
problem but, you do not need to create any object of shape. In such case, you can declare shape as a
abstract class. If you try to create object of a abstract class, compiler shows error.
Declaration of a Abstract Class
If expression =0 is added to a virtual function then, that function is becomes pure virtual function. Note
that, adding =0 to virtual function does not assign value, it simply indicates the virtual function is a pure
function. If a base class contains at least one virtual function then, that class is known as abstract class.
#include <iostream>
using namespace std;
int main()
{
Square s;
Circle c;
cout<<"Enter length to calculate area of a square: ";
s.get_data();
cout<<"Area of square: "<<s.area();
cout<<"\nEnter radius to calcuate area of a circle:";
c.get_data();
cout<<"Area of circle: "<<c.area();
return 0;
}
In this program, pure virtual function virtual float area() = 0; is defined inside class Shape, so this
class is an abstract class and you cannot create object of class Shape