OOSD UNIT 4
OOSD UNIT 4
OOSD UNIT 4
C++ Comments:
C++ introduces a new comment symbol //(double slash). Comments start with a
double slash symbol and terminate at the end of line. A comment may start any where in the line and
what ever follows till the end of line is ignored. Note that there is no closing symbol.
The double slash comment is basically a single line comment. Multi line comments can be
written as follows:
// this is an example of
// c++ program
// thank you
The c comment symbols /* ….*/ are still valid and more suitable for multi line comments.
Output Operator:
The statement cout <<”Hello, world” displayed the string with in quotes on the screen. The identifier
cout can be used to display individual characters, strings and even numbers. It is a predefined object
that corresponds to the standard output stream. Stream just refers to a flow of data and the standard
Output stream normally flows to the screen display. The cout object, whose properties are defined in
iostream.h represents that stream. The insertion operator << also called the ‘put to’ operator directs
the information on its right to the object on its left.
Return Statement:
In C++ main ( ) returns an integer type value to the operating system. Therefore every main (
) in C++ should end with a return (0) statement, otherwise a warning or an error might occur.
Input Operator:
The statement
cin>> number 1;
is an input statement and causes. The program to wait for the user to type in a number. The number
keyed in is placed in the variable number1. The identifier cin is a predefined object in C++ that
corresponds to the standard input stream. Here this stream represents the key board.
The operator >> is known as get from operator. It extracts value from the keyboard
and assigns it to the variable on its right.
Cascading Of I/O Operator:
cout<<”sum=”<<sum<<”\n”;
cout<<”sum=”<<sum<<”\n”<<”average=”<<average<<”\n”;
cin>>number1>>number2;
Structure Of A Program :
Probably the best way to start learning a programming language is by writing a program. Therefore,
here is our first program:
// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
Output:-Hello World!
The first panel shows the source code for our first program. The second one shows the result of the
program once compiled and executed. The way to edit and compile a program depends on the
compiler you are using. Depending on whether it has a Development Interface or not and on its
version. Consult the compilers section and the manual or help included with your compiler if you
have doubts on how to compile a C++ console program.
The previous program is the typical program that programmer apprentices write for the first time,
and its result is the printing on screen of the "Hello World!" sentence. It is one of the simplest
programs that can be written in C++, but it already contains the fundamental components that every
C++ program has. We are going to look line by line at the code we have just written:
// my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are considered comments and do
not have any effect on the behavior of the program. The programmer can use them to include short
explanations or observations within the source code itself. In this case, the line is a brief description
of what our program is.
#include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code
lines with expressions but indications for the compiler's preprocessor. In this case the directive
#include<iostream> tells the preprocessor to include the iostream standard file. This specific file
(iostream) includes the declarations of the basic standard input-output library in C++, and it is
included because its functionality is going to be used later in the program.
using namespace std;
All the elements of the standard C++ library are declared within what is called a namespace, the
namespace with the name std. So in order to access its functionality we declare with this expression
that we will be using these entities. This line is very frequent in C++ programs that use the standard
library, and in fact it will be included in most of the source codes included in these tutorials.
int main ()
This line corresponds to the beginning of the definition of the main function. The main function is
the point by where all C++ programs start their execution, independently of its location within the
source code. It does not matter whether there are other functions with other names defined before or
after it – the instructions contained within this function's definition will always be the first ones to be
executed in any C++ program. For that same reason, it is essential that all C++ programs have a main
function.
The word main is followed in the code by a pair of parentheses (()). That is because it is a function
declaration: In C++, what differentiates a function declaration from other types of expressions are
these parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters
within them.
Right after these parentheses we can find the body of the main function enclosed in braces ({}).
What is contained within these braces is what the function does when it is executed.
cout << "Hello World!";
This line is a C++ statement. A statement is a simple or compound expression that can actually
produce some effect. In fact, this statement performs the only action that generates a visible effect in
our first program.
cout represents the standard output stream in C++, and the meaning of the entire statement is to
insert a sequence of characters (in this case the Hello World sequence of characters) into the standard
output stream (which usually is the screen).
cout is declared in the iostream standard file within the std namespace, so that's why we needed to
include that specific file and to declare that we were going to use this specific namespace earlier in
our code.
Notice that the statement ends with a semicolon character (;). This character is used to mark the end
of the statement and in fact it must be included at the end of all expression statements in all C++
programs (one of the most common syntax errors is indeed to forget to include some semicolon after
a statement).
return 0;
The return statement causes the main function to finish. return may be followed by a return code (in
our example is followed by the return code 0). A return code of 0 for the main function is generally
interpreted as the program worked as expected without any errors during its execution. This is the
most usual way to end a C++ console program.
You may have noticed that not all the lines of this program perform actions when the code is
executed. There were lines containing only comments (those beginning by //). There were lines with
directives for the compiler's preprocessor (those beginning by #). Then there were lines that began
the declaration of a function (in this case, the main function) and, finally lines with statements (like
the insertion into cout), which were all included within the block delimited by the braces ({}) of the
main function.
The program has been structured in different lines in order to be more readable, but in C++, we do
not have strict rules on how to separate instructions in different lines. For example, instead of
int main ()
{
cout << " Hello World!";
return 0;
}
int main ()
{
cout << "Hello World!";
return 0;
}
All in just one line and this would have had exactly the same meaning as the previous code.
In C++, the separation between statements is specified with an ending semicolon (;) at the end of
each one, so the separation in different code lines does not matter at all for this purpose. We can
write many statements per line or write a single statement that takes many code lines. The division of
code in different lines serves only to make it more legible and schematic for the humans that may
read it.
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}
In this case, we performed two insertions into cout in two different statements. Once again, the
separation in different lines of code has been done just to give greater readability to the program,
since main could have been perfectly valid defined this way:
int main ()
{
cout << " Hello World! ";
cout << " I'm a C++ program ";
return 0;
}
We were also free to divide the code into more lines if we considered it more convenient:
int main ()
{
cout << "Hello World!";
cout << "I'm a C++ program";
return 0;
}
And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by #) are out of this general rule since they are not
statements. They are lines read and processed by the preprocessor and do not produce any code by
themselves. Preprocessor directives must be specified in their own line and do not have to end with a
semicolon (;).
• Include files
• Class declaration
• Class functions, definition
• Main function program
Example :-
# include<iostream.h>
class person
{
char name[30];
int age;
public:
void getdata(void);
void display(void);
};
void display()
{
cout<<”\n name:”<<name;
cout<<”\n age:”<<age;
}
int main( )
{
person p;
p.getdata();
p.display();
return(0);
}
TOKENS:
The smallest individual units in program are known as tokens. C++ has the following
tokens.
i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators
KEYWORDS:
The keywords implement specific C++ language feature. They are explicitly reserved
identifiers and can’t be used as names for the program variables or other user defined program
elements. The keywords not found in ANSI C are shown in red letter.
C++ KEYWORDS:
IDENTIFIERS:
Identifiers refers to the name of variable , functions, array, class etc. created by programmer. Each
language has its own rule for naming the identifiers.
In ANSI C the maximum length of a variable is 32 chars but in c++ there is no bar.
BASIC DATA TYPES IN C++
C ++ Data Types
Both C and C++ compilers support all the built in types. With the exception of void the basic
datatypes may have several modifiers preceding them to serve the needs of various situations. The
modifiers signed, unsigned, long and short may applied to character and integer basic data types.
However the modifier long may also be applied to double.
usigned 1 0 to 265
1) To specify the return type of function when it is not returning any value.
2) To indicate an empty argument list to a function.
Example:
Void function(void);
Example:
Void *gp;
Assigning any pointer type to a void pointer without using a cast is allowed in both C and ANSI C.
In ANSI C we can also assign a void pointer to a non-void pointer without using a cast to non void
pointer type. This is not allowed in C ++.
Example:
void *ptr1;
void *ptr2;
Are valid statement in ANSI C but not in C++. We need to use a cast operator.
ptr2=(char * ) ptr1;
We have used user defined data types such as struct,and union in C. While these more features have
been added to make them suitable for object oriented programming. C++ also permits us to define
another user defined data type known as class which can be used just like any other basic data type to
declare a variable. The class variables are known as objects, which are the central focus of oops.
An enumerated data type is another user defined type which provides a way for
attaching names to number, these by increasing comprehensibility of the code. The enum keyword
automatically enumerates a list of words by assigning them values 0,1,2 and soon. This facility
provides an alternative means for creating symbolic.
Example:
enum colour{red,blue,green,yellow}
The enumerated data types differ slightly in C++ when compared with ANSI C. In C++, the
tag names shape, colour, and position become new type names. That means we can declare new
variables using the tag names.
Example:
ANSI C defines the types of enums to be ints. In C++,each enumerated data type retains its
own separate type. This means that C++ does not allow an int value to be automatically converted to
an enum.
Example:
Example:
By default, the enumerators are assigned integer values starting with 0 for the first
enumerator, 1 for the second and so on. We can also write
Example:
enum{off,on};
Here off is 0 and on is 1.these constants may be referenced in the same manner as regular constants.
Example:
int switch-1=off;
int switch-2=on;
ANSI C permits an enum defined with in a structure or a class, but the enum is
globally visible. In C++ an enum defined with in a class is local to that class.
SYMBOLIC CONSTANT:
In both C and C++, any value declared as const can’t be modified by the program in any way.
In C++, we can use const in a constant expression. Such as
This would be illegal in C. const allows us to create typed constants instead of having to use #defme to
create constants that have no type information.
const size=10;
Means
DECLARATION OF VARIABLES:
In ANSIC C all the variable which is to be used in programs must be declared at the beginning of the
program .But in C++ we can declare the variables any whose in the program where it requires .This makes the
program much easier to write and reduces the errors that may be caused by having to scan back and forth. It
also makes the program easier to understand because the variables are declared in the context of their use.
Example:
main()
{
float x,average;
float sum=0;
for(int i=1;i<5;i++)
{
cin>>x;
sum=sum+x
}
float average;
average=sum/x;
cout<<average;
}
REFERENCE VARIABLES:
C++interfaces a new kind of variable known as the reference variable. A references variable
provides an alias.(alternative name) for a previously defined variable. For example ,if we make the
variable sum a reference to the variable total, then sum and total can be used interchangeably to represent
the variuble.
A reference variable is created as follows:
Synatx: Datatype & reference –name=variable name;
Example:
float total=1500;
float &sum=total;
Here sum is the alternative name for variables total, both the variables refer to the same data object in the
memory .
A reference variable must be initialized at the time of declaration .
Note that C++ assigns additional meaning to the symbol & here & is not an address operator
.The notation float & means reference to float.
Example:
int n[10];
int &x=n[10];
char &a=’\n’;
OPERATORS IN C++ :
C++ has a rich set of operators. All C operators are valid in C++ also. In addition. C++
introduces some new operators.
Like C,C++ is also a block-structured language. Block -structured language. Blocks and
scopes can be used in constructing programs. We know same variables can be declared in different
blocks because the variables declared in blocks are local to that function.
Blocks in C++ are often nested.
Example:
{
Int x =10;
}
Block2 contained in block l .Note that declaration in an inner block hides a declaration of the
same variable in an outer block and therefore each declaration of x causes it to refer to a different data object .
With in the inner block the variable x will refer to the data object declared there in.
In C,the global version of a variable can't be accessed from with in the inner block.
C++ resolves this problem by introducing a new operator :: called the scope resolution operator .This can be
used to uncover a hidden variable.
Example:
#include <iostrcam.h>
int m=10;
main()
{
int m=20;
{
int k=m;
int m=30;
cout<<”we are in inner block”;
cout<<"k="<<k<<endl;
cout<<"m="<<m<<endl;
cout<<":: m="<<:: m<<endl;
}
cout<<”\n we are in outer block \n”;
cout<<"m="<<m<<endl;
cout<<":: m="<<:: m<<endl;
}
C++ also support those functions it also defines two unary operators new and delete that
perform the task of allocating and freeing the memory in a better and easier way.
The new operator can be used to create objects of any type. Syntax: pointer-
Example:
p=new int; q=new int;
float *p=newfloat;
*p=25;
*q=7.5;
Assign 25 to the newly created int object and 7.5 to the float object.We can also initialize the memory
using the new operator.
Syntax:
int *p=ne\v int(25);
float *q =new float(7.5);
new can be used to create a memory space for any data type including user defined such as
arrays,structures,and classes .The general form for a one-dimensional array is:
If a data object is no longer needed, it is destroyed to release the memory space for reuse.
Example:
delete p;
delete q;
If we want to free a dynamically allocated array ,we must use the following
form of delete.
MANIPULATERS:
Manipulators are operator that are used to format the data display. The most commonly manipulators are
endl and setw.
The endl manipulator, when used in an output statement, causes a line feed to be insert.(just like \n)
Example:
cout<<”m=”<<m<<endl;
cout<<”n=”<<n<<endl;
cout<<”p=”<<p<<endl;
If we assume the values of the variables as 2597,14 and 175 respectively
m=2597; n=14;
p=175
It was want to print all nos in right justified way use setw which specify a common field width
for all the nos.
Example: cout<<setw(5)<<sum<<endl;
cout<<setw(10)<<”basic”<<setw(10<<basic<<endl;
Cout<<setw(10)<<”allowance”<<setw(10<<allowance<<endl;
cout<<setw(10)<<”total=”<<setw(10)<<total;
CONTROL STRUCTURES:
Like c,c++, supports all the basic control structures and implements them various control statements.
The if statement:
1. simple if statement
Simple if statement:
if (condition)
Action;
If (condition)
Statment1
Else
Statement2
This is a multiple-branching statement where, based on a condition, the control is transferred to one of the many
possible points;
Switch(expr)
case 1:
action1;
break;
case 2:
action2;
break;
..
..
default:
message
Syn:
While(condition)
Stements
}
The do-while statement:
Syn:
do
Stements
} while(condition);
for(expression1;expression2;expression3)
Statements;
Statements;
}
Here’s a general syntax for a function in C++:
Function Syntax:
// Function body
• return_type: Specifies the type of value the function returns (e.g., int, double,
void if no return value).
#include <iostream>
// Function definition
void greet() {
int main() {
greet();
return 0;
}
Explanation:
#include <iostream>
return a + b;
int main() {
int result = add(5, 3); // Calling the add function with 5 and 3 as arguments
cout << "The result of addition is: " << result << endl;
return 0;
Explanation:
• The main() function calls add() with 5 and 3 and stores the result in result, which
is then printed.
#include <iostream>
int temp = x;
x = y;
y = temp;
int main() {
int a = 5, b = 10;
cout << "Before swap: a = " << a << ", b = " << b << endl;
swap(a, b);
cout << "After swap: a = " << a << ", b = " << b << endl;
return 0;
Explanation:
• The function swap() uses reference parameters (int &x, int &y), which allows the
function to modify the original variables passed to it.
• In main(), the values of a and b are swapped using the swap() function.
Output:
Before swap: a = 5, b = 10
1. Void Functions: Functions that do not return a value use the void return type.
3. Return Value: Functions that return a value must specify the type of value they
return.
Function with Call by Value and Call by Reference in C++
Call by Value
In call by value, the function gets a copy of the argument. Changes made inside the
function do not affect the original value.
#include <iostream>
cout << "Inside callByValue function: " << num << endl;
int main() {
cout << "Before callByValue function: " << value << endl;
callByValue(value);
cout << "After callByValue function: " << value << endl; // Original value remains
unchanged
return 0;
Output:
In call by reference, the function gets a reference to the original variable. Changes
made inside the function affect the original value.
#include <iostream>
cout << "Inside callByReference function: " << num << endl;
int main() {
cout << "Before callByReference function: " << value << endl;
callByReference(value);
cout << "After callByReference function: " << value << endl; // Original value is
modified
return 0;
Output:
Modification Does not affect the original variable. Affects the original variable.
When you don't want the original When you want to modify the
Use Case
data to be changed. original data.
Inline Functions in C++
In C++, an inline function is a function where the compiler attempts to insert the
function's code directly into the calling code, instead of performing a regular function
call. This can improve performance by eliminating the overhead of function calls,
especially for small functions that are called frequently.
// function body
return value;
Example:
#include <iostream>
return a + b;
int main() {
return 0;
}
How Inline Functions Work:
• When an inline function is called, the compiler replaces the function call with
the function's code.
• This can reduce function call overhead, especially for small functions that are
called many times.
2. Code Optimization: Can help the compiler optimize the code by reducing the
function call overhead.
3. Type Safety: Unlike macros, inline functions provide type checking and are safer
to use.
1. Code Bloat: If the inline function is large or used in many places, it can increase
the size of the executable, which can impact memory usage.
2. Limited Usage: The compiler can ignore the inline keyword if it determines that
inlining isn't beneficial (e.g., for large functions).
Macros vs Inline Functions
In C++, macros are a feature of the preprocessor and are quite different from inline
functions. Macros can be used for code substitution before the program is compiled.
Example of a Macro:
#include <iostream>
int main() {
return 0;
• Macros are handled by the preprocessor: They are replaced with the code at
compile-time before the actual compilation begins.
• In the above example, the macro ADD(5, 3) is expanded to ((5) + (3)), which is
then processed by the compiler.
• No type checking: Macros don't provide type safety or error checking like inline
functions do.
Disadvantages of Macros:
1. No Type Safety: Macros don’t check types, which can lead to unexpected
behavior. For example, the macro ADD(a, b) can cause errors if a and b are not
numbers.
3. Potential for Side Effects: Since macros expand code at compile time, if the
arguments have side effects (like i++), those side effects can occur multiple
times, leading to bugs.
Function overloading in C++ allows you to define multiple functions with the same
name but different parameters. The compiler distinguishes these functions based on
the number or types of arguments passed. Function overloading helps improve code
readability and allows for more flexible function calls.
1. Function Name: All overloaded functions must have the same name.
2. Different Parameters: They must differ in the number or types of parameters (or
both).
#include <iostream>
class Calculator {
public:
return a + b;
return a + b + c;
return a + b;
};
int main() {
Calculator calc;
cout << "Sum of 2 and 3: " << calc.add(2, 3) << endl; // Calls add(int, int)
cout << "Sum of 1.5 and 2.5: " << calc.add(1.5f, 2.5f) << endl; // Calls add(float, float)
cout << "Sum of 1, 2, and 3: " << calc.add(1, 2, 3) << endl; // Calls add(int, int, int)
return 0;
Output:
Sum of 2 and 3: 5
Sum of 1, 2, and 3: 6
Default arguments allow a function to be called without passing all the arguments
explicitly. When an argument is not passed, the default value is used. This can be useful
for simplifying function calls and making your code more flexible.
• Default values are provided in the function declaration, not in the definition (if
separated).
• You can specify default values for parameters from right to left.
2. Once a parameter has a default argument, all parameters to its right must also
have default arguments.
3. If an argument is passed when calling the function, the default value is ignored.
Example of Default Arguments:
#include <iostream>
class Printer {
public:
};
int main() {
Printer printer;
printer.printMessage();
// Calling function with one argument, second argument uses default value
printer.printMessage("Custom message");
return 0;
}
Output:
Hello, World!
Custom message
Custom message
Custom message
1. Default arguments allow you to have a function that can be called with fewer
arguments than the number defined in the function declaration.
2. Overloaded functions can have different default arguments, but the choice of
which overloaded function is called is still based on the function signature
(parameter count and types).
3. Default arguments can provide flexibility in function calls, allowing for optional
parameters, but it is important to manage default values in the right order.
#include <iostream>
class Display {
public:
};
int main() {
Display disp;
return 0;
Output:
Default Message
Custom Message
Custom Message
Custom Message
Friend Function in C++
A friend function in C++ is a function that is not a member of a class but has access to
the class’s private and protected members. Friend functions can be regular functions or
methods from another class that are given special access to a particular class's private
or protected data. This is useful when you need a function that interacts closely with a
class but doesn't logically belong as a member of that class.
1. A friend function is declared using the friend keyword inside the class.
4. Friend functions are often used to implement operators that need direct access
to private data (like overloading operators).
class ClassName {
};
#include <iostream>
class Box {
private:
int length;
int width;
public:
// Constructor
};
void display(Box& b) {
cout << "Length: " << b.length << ", Width: " << b.width << endl;
int main() {
display(b);
return 0;
Output:
In this example, the display function is not a member of the Box class, but it can access
the private data members length and width because it is declared as a friend function.
Virtual Function in C++
1. A function is made virtual by using the virtual keyword in the base class.
2. If a function is overridden in a derived class, C++ ensures that the derived class
version of the function is called even when a base class pointer or reference is
used.
4. If a function is not virtual, the base class version is called, even when using a
base class pointer or reference.
class Base {
public:
};
Example of Virtual Function:
#include <iostream>
class Animal {
public:
// Virtual function
};
public:
};
public:
};
int main() {
Animal* animal;
Dog dog;
Cat cat;
animal = &dog;
animal = &cat;
return 0;
Output:
Bark
Meow
Key Differences Between Friend and Virtual Functions:
Access to private/protected
Access Has access to private/protected
members depends on the object's
Control members of the class.
context.