0% found this document useful (0 votes)
34 views35 pages

Oosd notes

Here are the notes of aktu

Uploaded by

kartik editz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views35 pages

Oosd notes

Here are the notes of aktu

Uploaded by

kartik editz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

MEERUT INSTITUTE OF ENGINEERING AND TECHNOLOGY

OBJECT ORIENTED SYSTEM DESIGN

KCS-054

UNIT 4

C++ INTRODUCTION

C++ is a middle-level programming language developed by Bjarne Stroustrup


starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as
Windows, Mac OS, and the various versions of UNIX.

Why to Learn C++?

C++ is a MUST for students and working professionals to become a great Software
Engineer. I will list down some of the key advantages of learning C++:

• C++ is very close to hardware, so you get a chance to work at a low level
which gives you lot of control in terms of memory management, better
performance and finally a robust software development.

• C++ programming gives you a clear understanding about Object Oriented


Programming. You will understand low level implementation of
polymorphism when you will implement virtual tables and virtual table
pointers, or dynamic type identification.

• C++ is one of the every green programming languages and loved by millions
of software developers. If you are a great C++ programmer then you will
never sit without work and more importantly you will get highly paid for
your work.

• C++ is the most widely used programming languages in application and


system programming. So you can choose your area of interest of software
development.

• C++ really teaches you the difference between compiler, linker and loader,
different data types, storage classes, variable types their scopes etc.
There are many C++ compilers available which you can use to compile and run
above mentioned program:

• Apple C++. Xcode

• Bloodshed Dev-C++

• Clang C++

• Cygwin (GNU C++)

• Mentor Graphics

• MINGW - "Minimalist GNU for Windows"

• GNU CC source

• IBM C++

• Intel C++

• Microsoft Visual C++

• Oracle C++

• HP C++

Applications of C++ Programming

As mentioned before, C++ is one of the most widely used programming languages.
It has it's presence in almost every area of software development. I'm going to list
few of them here:

• Application Software Development - C++ programming has been used in


developing almost all the major Operating Systems like Windows, Mac OSX
and Linux. Apart from the operating systems, the core part of many
browsers like Mozilla Firefox and Chrome have been written using C++.
C++ also has been used in developing the most popular database system
called MySQL.
• Programming Languages Development - C++ has been used extensively in
developing new programming languages like C#, Java, JavaScript, Perl,
UNIX’s C Shell, PHP and Python, and Verilog etc.

• Computation Programming - C++ is the best friends of scientists because of


fast speed and computational efficiencies.

• Games Development - C++ is extremely fast which allows programmers to


do procedural programming for CPU intensive functions and provides
greater control over hardware, because of which it has been widely used in
development of gaming engines.

• Embedded System - C++ is being heavily used in developing Medical and


Engineering Applications like softwares for MRI machines, high-end
CAD/CAM systems etc.

C++ Program Structure


Live Demo
#include <iostream.h>
#include<conio.h>

// main() is where program execution begins.


void main() {
cout << "Hello World"; // prints Hello World

The C++ language defines several headers, which contain information that is either
necessary or useful to your program. For this program, the header <iostream> is
needed.

The next line '// main() is where program execution begins.' is a single-line
comment available in C++. Single-line comments begin with // and stop at the end
of the line.

The line main() is the main function where program execution begins.
The next line cout << "Hello World"; causes the message "Hello World" to be
displayed on the screen.

C++ Data Types


While writing program in any language, you need to use various variables to store
various information. Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you reserve some space in
memory.

You may like to store information of various data types like character, wide
character, integer, floating point, double floating point, boolean etc. Based on the
data type of a variable, the operating system allocates memory and decides what
can be stored in the reserved memory.

Primitive Built-in Types

C++ offers the programmer a rich assortment of built-in as well as user defined
data types. Following table lists down seven basic C++ data types −

Type Keyword

Boolean bool

Character char

Integer int

Floating point float

Double floating point double


Valueless void

Wide character wchar_t

Several of the basic types can be modified using one or more of these type
modifiers −

• signed

• unsigned

• short

• long

The following table shows the variable type, how much memory it takes to store
the value in memory, and what is maximum and minimum value which can be
stored in such type of variables.

Type Typical Bit Width Typical Range

char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

int 4bytes -2147483648 to 2147483647


unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int 2bytes 0 to 65,535

signed short int 2bytes -32768 to 32767

long int 8bytes -2,147,483,648 to 2,147,483,647

signed long int 8bytes same as long int

unsigned long int 8bytes 0 to 4,294,967,295

long long int 8bytes -(2^63) to (2^63)-1

unsigned long long int 8bytes 0 to 18,446,744,073,709,551,615

float 4bytes

double 8bytes

long double 12bytes


wchar_t 2 or 4 bytes 1 wide character

C++ Variable Types


A variable provides us with named storage that our programs can manipulate. Each
variable in C++ has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and
the set of operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C++ is case-sensitive.

Sr.No Type & Description

1 bool

Stores either value true or false.

2 char

Typically a single octet (one byte). This is an integer type.

3 int

The most natural size of integer for the machine.

4 float

A single-precision floating point value.

5 double
A double-precision floating point value.

6 void

Represents the absence of type.

7 wchar_t

A wide character type.

C++ also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Reference, Data
structures, and Classes.

Variable Definition in C++

A variable definition tells the compiler where and how much storage to create for
the variable. A variable definition specifies a data type, and contains a list of one or
more variables of that type as follows −

type variable_list;

Variables can be initialized (assigned an initial value) in their declaration. The


initializer consists of an equal sign followed by a constant expression as follows −

type variable_name = value;

Variable Scope in C++

A scope is a region of the program and broadly speaking there are three places,
where variables can be declared −

• Inside a function or a block which is called local variables,


• In the definition of function parameters which is called formal parameters.

• Outside of all functions which is called global variables.

We will learn what is a function and it's parameter in subsequent chapters. Here let
us explain what are local and global variables.

Identifiers in C++

The C++ identifier is a name used to identify a variable, function, class, module, or
any other user-defined item. An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).

C++ does not allow punctuation characters such as @, $, and % within identifiers.
C++ is a case-sensitive programming language. Thus, Manpower and manpower
are two different identifiers in C++.

Here are some examples of acceptable identifiers −

mohd Piyush abc move_name a_123

myname50 _temp j a23b9 retVal

Enumerated Types or Enums in C++

Enumerated type (enumeration) is a user-defined data type which can be assigned


some limited values. These values are defined by the programmer at the time of
declaring the enumerated type.

When we assign a float value in a character value then compiler generates an error
in the same way if we try to assign any other value to the enumerated data types
the compiler generates an error. Enumerator types of values are also known as
enumerators. It is also assigned by zero the same as the array. It can also be used
with switch statements.

For example: If a gender variable is created with value male or female. If any
other value is assigned other than male or female then it is not appropriate. In this
situation, one can declare the enumerated type in which only male and female
values are assigned.

Syntax:

enum enumerated-type-name{value1, value2, value3…..valueN};

enum keyword is used to declare enumerated types after that enumerated type
name was written then under curly brackets possible values are defined. After
defining Enumerated type variables are created. It can be created in two types:

1. It can be declared during declaring enumerated types, just add the name of
the variable before the semicolon.or,

2. Beside this, we can create enumerated type variables as same as the normal
variables.
enumerated-type-name variable-name = value;

By default, the starting code value of the first element of enum is 0 (as in the case
of array) . But it can be changed explicitly.
For example:

//first_enum is the enumerated-type-name


enum first_enum{value 1, value2=10, value3};

first_enum e;
e=value3;
cout<<e;

Output:
11
#include <iostream.h>
using namespace std;

int main()
{
// Defining enum Gender
enum Gender { Male, Female };

// Creating Gender type variable


Gender gender = Male;

switch (gender)
{
case Male:
cout << "Gender is Male";
break;
case Female:
cout << "Gender is Female";
break;
default:
cout << "Value can be Male or Female";
}
return 0;
}

Operators in C++

An operator is a symbol that tells the compiler to perform specific mathematical or


logical manipulations. C++ is rich in built-in operators and provide the following
types of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators

Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after B % A will give 0


an integer division

++ Increment operator, increases integer A++ will give 11


value by one

-- Decrement operator, decreases integer A-- will give 9


value by one

Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then –

Operator Description Example

== Checks if the values of two operands are (A == B) is not true.


equal or not, if yes then condition
becomes true.

!= Checks if the values of two operands are (A != B) is true.


equal or not, if values are not equal then
condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right operand, if
yes then condition becomes true.

< Checks if the value of left operand is less (A < B) is true.


than the value of right operand, if yes
then condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of right
operand, if yes then condition becomes
true.

<= Checks if the value of left operand is less (A <= B) is true.


than or equal to the value of right
operand, if yes then condition becomes
true.
Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then −

Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then condition
becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true.


two operands is non-zero, then condition
becomes true.

! Called Logical NOT Operator. Use to !(A && B) is true.


reverses the logical state of its operand. If
a condition is true, then Logical NOT
operator will make false.

Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are as follows −
p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table.
Assume variable A holds 60 and variable B holds 13, then −
Operator Description Example

& Binary AND Operator copies a bit to the (A & B) will give 12 which is 0000
result if it exists in both operands. 1100

| Binary OR Operator copies a bit if it (A | B) will give 61 which is 0011 1101


exists in either operand.

^ Binary XOR Operator copies the bit if it


(A ^ B) will give 49 which is 0011 0001
is set in one operand but not both.

~ Binary Ones Complement Operator is (~A ) will give -61 which is 1100 0011
unary and has the effect of 'flipping' bits. in 2's complement form due to a signed
binary number.

<< Binary Left Shift Operator. The left


operands value is moved left by the A << 2 will give 240 which is 1111
number of bits specified by the right 0000
operand.

>> Binary Right Shift Operator. The left


operands value is moved right by the
A >> 2 will give 15 which is 0000 1111
number of bits specified by the right
operand.
Assignment Operators
There are following assignment operators supported by C++ language –

Operator Description Example

= Simple assignment operator, Assigns


C = A + B will assign value of A + B
values from right side operands to left side
into C
operand.

+= Add AND assignment operator, It adds


right operand to the left operand and assign C += A is equivalent to C = C + A
the result to left operand.

-= Subtract AND assignment operator, It


subtracts right operand from the left
C -= A is equivalent to C = C - A
operand and assign the result to left
operand.

*= Multiply AND assignment operator, It


multiplies right operand with the left
C *= A is equivalent to C = C * A
operand and assign the result to left
operand.

/= Divide AND assignment operator, It


divides left operand with the right operand C /= A is equivalent to C = C / A
and assign the result to left operand.

%= Modulus AND assignment operator, It


takes modulus using two operands and C %= A is equivalent to C = C % A
assign the result to left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2


^= Bitwise exclusive OR and assignment
C ^= 2 is same as C = C ^ 2
operator.

|= Bitwise inclusive OR and assignment


C |= 2 is same as C = C | 2
operator.

Misc Operators
The following table lists some other operators that C++ supports.

Sr.No Operator & Description

1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is
integer, and will return 4.

2 Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise
returns value of Y.

3 ,
Comma operator causes a sequence of operations to be performed. The value of the
entire comma expression is the value of the last expression of the comma-separated list.

4 . (dot) and -> (arrow)


Member operators are used to reference individual members of classes, structures, and
unions.

5 Cast
Casting operators convert one data type to another. For example, int(2.2000) would
return 2.

6 &
Pointer operator & returns the address of a variable. For example &a; will give actual
address of the variable.
7 *
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable
var.

Operators Precedence in C++

Operator precedence determines the grouping of terms in an expression. This


affects how an expression is evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator has higher precedence than
the addition operator −
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has
higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right


Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

C++ decision making statements

Decision making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.
C++ programming language provides following types of decision making
statements.
Sr.No Statement & Description

1 if statement
An ‘if’ statement consists of a boolean expression followed by one or more statements.

2 if...else statement
An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when
the boolean expression is false.

3 switch statement
A ‘switch’ statement allows a variable to be tested for equality against a list of values.

4 nested if statements
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).
5 nested switch statements
You can use one ‘switch’ statement inside another ‘switch’ statement(s).

C++ Loop Types:

There may be a situation, when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times

C++ programming language provides the following type of loops to handle looping
requirements.
Sr.No Loop Type & Description

1 while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.

2 for loop
Execute a sequence of statements multiple times and abbreviates the code that manages
the loop variable.

3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the loop body.

4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
C++ supports the following control statements.
Sr.No Control Statement & Description

1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.

3 goto statement
Transfers control to the labeled statement. Though it is not advised to use goto
statement in your program.

Type Conversion/Type Casting in C++

A type cast is basically a conversion from one type to another. There are two types
of type conversion:
1. Implicit Type Conversion Also known as ‘automatic type conversion’.
• Done by the compiler on its own, without any external trigger from
the user.
• Generally takes place when in an expression more than one data type
is present. In such condition type conversion (type promotion) takes
place to avoid lose of data.
• All the data types of the variables are upgraded to the data type of the
variable with largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
• It is possible for implicit conversions to lose information, signs can be
lost (when signed is implicitly converted to unsigned), and overflow
can occur (when long long is implicitly converted to float).
Example of Explicit type conversion:

#include <iostream>
using namespace std;

int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

cout << "x = " << x << endl


<< "y = " << y << endl
<< "z = " << z << endl;

return 0;
}
Output:
x = 107
y=a
z = 108

Explicit Type Conversion: This process is also called type casting and it is user-
defined. Here the user can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
• Converting by assignment: This is done by explicitly defining the required
type in front of the expression in parenthesis. This can be also considered as
forceful casting.

Syntax:
(type) expression
where type indicates the data type to which the final result is converted.

#include <iostream>
using namespace std;
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
cout << "Sum = " << sum;
return 0;
}
Output:
Sum = 2

Conversion using Cast operator: A Cast operator is an unary operator which


forces one data type to be converted into another data type.
C++ supports four types of casting:
1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast

#include <iostream>
using namespace std;
int main()
{
float f = 3.5;

// using cast operator


int b = static_cast<int>(f);

cout << b;
}
Output:
3

Advantages of Type Conversion:


• This is done to take advantage of certain features of type hierarchies or type
representations.
• It helps to compute expressions containing variables of different data types.

Functions in C++

A function is a set of statements that take inputs, do some specific computation and
produces output.
The idea is to put some commonly or repeatedly done task together and make a function
so that instead of writing the same code again and again for different inputs, we can call
the function.
The general form of a function is:
return_type function_name([ arg1_type arg1_name, ... ])
{
code //function to performed
}

Why do we need functions?


• Functions help us in reducing code redundancy. If functionality is performed
at multiple places in software, then rather than writing the same code, again
and again, we create a function and call it everywhere. This also helps in
maintenance as we have to change at one place if we make future changes to
the functionality.
• Functions make code modular. Consider a big file having many lines of
codes. It becomes really simple to read and use the code if the code is
divided into functions.
• Functions provide abstraction. For example, we can use library functions
without worrying about their internal working.
FunctionDeclaration:
A function declaration tells the compiler about the number of parameters function
takes, data-types of parameters and return type of function. Putting parameter
names in function declaration is optional in the function declaration, but it is
necessary to put them in the definition.

Parameter Passing to functions


The parameters passed to function are called actual parameters. For example, in
the above program 10 and 20 are actual parameters.
The parameters received by function are called formal parameters. For example,
in the above program x and y are formal parameters.
There are two most popular ways to pass parameters.

Pass/call by Value: In this parameter passing method, values of actual parameters


are copied to function’s formal parameters and the two types of parameters are
stored in different memory locations. So any changes made inside functions are not
reflected in actual parameters of caller.

Pass/call by Reference :Both actual and formal parameters refer to same locations,
so any changes made inside the function are actually reflected in actual parameters
of caller.
Parameters are always passed by value in C++. For example in the below code,
value of x is not modified using the function fun().

Call by value:

#include <iostream>
using namespace std;
void fun(int x) {
x = 30; }
int main() {
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}

Output:
x = 20

Call by reference:

#include <iostream>
using namespace std;
void fun(int *ptr)
{
*ptr = 30;
}
int main() {
int x = 20;
fun(&x);
cout << "x = " << x;
return 0;
}

What is inline function?


C++ provides an inline functions to reduce the function call overhead. Inline
function is a function that is expanded in line when it is called. When the inline
function is called whole code of the inline function gets inserted or substituted at
the point of inline function call. This substitution is performed by the C++
compiler at compile time. Inline function may increase efficiency if it is small.

Why inline function required?

 When the program executes the function call instruction the CPU stores the
memory address of the instruction following the function call, copies the
arguments of the function on the stack and finally transfers control to the
specified function.
 The CPU then executes the function code, stores the function return value in
a predefined memory location/register and returns control to the calling
function.
 This can become overhead if the execution time of function is less than the
switching time from the caller function to called function (callee). For
functions that are large and/or perform complex tasks, the overhead of the
function call is usually insignificant compared to the amount of time the
function takes to run. However, for small, commonly-used functions, the
time needed to make the function call is often a lot more than the time
needed to actually execute the function’s code. This overhead occurs for
small functions because execution time of small function is less than the
switching time.

inline return-type function-name(parameters)


{
// function code
}

Compiler may not perform inlining in such circumstances like:


1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn’t exist
in function body.
5) If a function contains switch or goto statement.

Inline functions provide following advantages:


1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when function is
called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform context
specific optimization on the body of function. Such optimizations are not possible
for normal function calls. Other optimizations can be obtained by considering the
flows of calling context and the called context.
5) Inline function may be useful (if it is small) for embedded systems because
inline can yield less code than the function call preamble and return.

#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
}
Output: The cube of 3 is: 27

Difference between Inline function and macros


 An inline function is defined by the inline keyword. Whereas the macros are
defined by the #define keyword.
 Through inline function, the class’s data members can be accessed. Whereas
macro can’t access the class’s data members.
 In the case of inline function, the program can be easily debugged. Whereas
in the case of macros, the program can’t be easily debugged.
 In the case of inline, the arguments are evaluated only once. Whereas in the
case of macro, the arguments are evaluated every time whenever macro is
used in the program.
 In C++, inline may be defined either inside the class or outside the class.
Whereas the macro is all the time defined at the beginning of the program.
 In C++, inside the class, the short length functions are automatically made
the inline functions. While the macro is specifically defined.
 Inline is not as widely used as macros. While the macro is widely used.
 Inline function is terminated by the curly brace at the end. While the macro
is not terminated by any symbol, it is terminated by a new line.

Function Overloading in C++

We can have multiple definitions for the same function name in the same
scope. The definition of the function must differ from each other by the
types and/or the number of arguments in the argument list. We cannot
overload function declarations that differ only by return type.

#include <iostream>
using namespace std;
class printData {
public:
void print(int i)
{
cout << "Printing int: " << i << endl;
}
void print(double f)
{
cout << "Printing float: " << f << endl;
}
void print(char* c)
{
cout << "Printing character: " << c << endl;
}
};

int main(void) {
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}

Output:

Printing int: 5
Printing float: 500.263
Printing character: Hello C++

Default Arguments in C++

A default argument is a value provided in a function declaration that is


automatically assigned by the compiler if the caller of the function doesn’t provide
a value for the argument with a default value.

#include<iostream>
using namespace std;
// A function with default arguments, it can be called with

int sum(int x, int y, int z=0, int w=0)


{
return (x + y + z + w);
}
int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Output:
25
50
80

Friend function in C++

A friend function can be given special grant to access private and protected
members. A friend function can be:
a) A method of another class
b) A global function

Following are some important points about friend functions and classes:

1) Friends should be used only for limited purpose. too many functions or external
classes are declared as friends of a class with protected or private data, it lessens
the value of encapsulation of separate classes in object-oriented programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a
friend of A automatically.
3) Friendship is not inherited
4) The concept of friends is not there in Java.
#include <iostream>
class A {
private:
int a;

public:
A() { a = 0; }
friend class B; // Friend Class
};

class B {
private:
int b;

public:
void showA(A& x)
{
// Since B is friend of A, it can access
// private members of A
std::cout << "A::a=" << x.a;
}
};

int main()
{
A a;
B b;
b.showA(a);
return 0;
}
Output:
A::a=0
Virtual Function in C++:

A virtual function is a member function which is declared within a base class and is re-
defined(Overriden) by a derived class. When you refer to a derived class object using a
pointer or a reference to the base class, you can call a virtual function for that object and
execute the derived class’s version of the function.
• Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
• They are mainly used to achieve Runtime polymorphism
• Functions are declared with a virtual keyword in base class.
• The resolving of function call is done at Run-time.

Rules for Virtual Functions


1. Virtual functions cannot be static and also cannot be a friend function of another
class.
2. Virtual functions should be accessed using pointer or reference of base class
type to achieve run time polymorphism.
3. The prototype of virtual functions should be same in base as well as derived
class.
4. They are always defined in base class and overridden in derived class. It is not
mandatory for derived class to override (or re-define the virtual function), in that
case base class version of function is used.
5. A class may have virtual destructor but it cannot have a virtual constructor.

#include <iostream>
using namespace std;

class base {
public:
virtual void print()
{
cout << "print base class" << endl;
}
void show()
{
cout << "show base class" << endl;
}
};

class derived : public base {


public:
void print()
{
cout << "print derived class" << endl;
}

void show()
{
cout << "show derived class" << endl;
}
};

int main()
{
base* bptr;
derived d;
bptr = &d;

// virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();
}

Output:

print derived class


show base class

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy