Sei sulla pagina 1di 31

Object oriented programming with C++ 16CSE43

Introduction to OOP and C++


16CSE43
Module 1
1.1 Evolution of Programming methodologies
The programming languages have evolved from machine languages, assembly languages to
high level languages to the current age of programming tools.

Machine Languages
Any computer can directly understand only its own machine language, defined by its hardware
architecture. Machine languages generally consist of numbers (ultimately reduced to 1s and 0s).
Such languages are cumbersome for humans.
Assembly Languages
Programming in machine language was simply too slow and tedious for most programmers.
Instead, they began using English like abbreviations to represent elementary operations.
These abbreviations formed the basis of assembly languages. Translator programs called
assemblers were developed to convert assembly-language programs to machine language.
Although assembly-language code is clearer to humans, it’s incomprehensible to computers until
translated to machine language.

High level languages


High-level languages allow you to write instructions that look almost like every day English and
contain commonly used mathematical expressions. Translator programs called compilers convert
high-level language programs into machine language.

I. Procedural languages
High level languages like C, Basic, FORTRAN and so on are known as procedural languages as
each and every statement in the program had to be specified to instruct the computer to do a
specific job.
Some Characteristics exhibited by procedure-oriented programming are:
• Emphasis is on doing things (algorithms).
• Large programs are divided into smaller programs known as functions.
• Most of the functions share global data.

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

• Data move openly around the system from function to function.


• Functions transform data from one form to another.
• Employs top-down approach in program design.

Limitations of Procedural approach

1. Procedural languages are difficult to relate with the real world objects.

(For example, if you want to develop a gaming application of car race, what data would you use
and what functions you would require is difficult questions to answer in a procedural approach.)
2. Procedural codes are very difficult to maintain, if the code grows larger.
3. The data, which is used in procedural languages are exposed to the whole program. So, there
is no security for the data

Applications of C
1. C is widely used for "system programming", including implementing operating systems
and embedded system applications. (Because C code, when written for portability, can be
used for most purposes, yet when needed, system-specific code can be used to access
specific hardware addresses and to perform type punning to match externally imposed
interface requirements, with a low run-time demand on system resources.)

2. C can also be used for website programming using CGI as a "gateway" for information
between the Web application, the server, and the browser.

3. C is often chosen over interpreted languages because of its speed, stability, and near-
universal availability.

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

II. object-oriented programming (OOP)


Object-oriented programming (OOP) is a programming language model organized around
objects rather than "actions" and data rather than logic.
Some of the features of object oriented programming are:
• Emphasis is on data rather than procedure.
• Programs are divided into what are known as objects.
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are ties together in the data structure.
• Data is hidden and cannot be accessed by external function.
• Objects may communicate with each other through function.
• New data and functions can be easily added whenever necessary.
• Follows bottom up approach in program design.

Principles of Object Oriented Programming **


a. Object
Objects are the basic run time entities in an object-oriented system. They may represent a person,
a place, a bank account, a table of data or any item that the program has to handle. They may
also represent user-defined data such as vectors, time and lists.
Object contains attributes and operations. The attributes are called data members because they
hold information. The functions that operate on these data are called methods or member
function.

b. Class
When you define a class, you define a blueprint for an object. 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.
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 similar types.
For examples, Mango, Apple and orange members of class fruit.
Classes are user-defined that types and behave like the built-in types of a programming language.
The syntax used to create an object is not different then the syntax used to create an integer
variable in C.

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

If fruit has been defines as a class, then the statement


Fruit Mango;
Will create an object mango belonging to the class fruit.

c. Data Abstraction and Encapsulation


The wrapping up of data and function into a single unit (called class) is known as encapsulation.
The data is not accessible to the outside world, and only those functions which are wrapped in
the class can access it. These functions provide the interface between the object’s data and the
program. This insulation of the data from direct access by the program is called data hiding or
information hiding.
Abstraction refers to the act of representing essential features without including the background
details or explanation. For example, a database system hides certain details of how data is stored
and created and maintained. Similar way, C++ classes provides different methods to the outside
world without giving internal detail about those methods and data.
d. Inheritance

Inheritance is the process by which objects of one class acquired the properties of objects of
another classes. It supports the concept of hierarchical classification. For example, teacher and
Student are part of class ‘Person’. The principal behind this sort of division is that each derived
class shares common characteristics with the class from which it is derived

e. Polymorphism
Polymorphism means one name, many forms. Polymorphism manifests itself by having multiple
methods all with the same name, but slightly different functionality.

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

There are 2 basic types of polymorphism. Overriding, also called run-time polymorphism, and
overloading, which is referred to as compile-time polymorphism.
This difference is, for method overloading, the compiler determines which method will be
executed, and this decision is made when the code gets compiled. Which method will be used for
method overriding is determined at runtime based on the dynamic type of an object.
An operation may exhibit different behavior is different instances. 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 overloading.

f. Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic 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.

g. 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, involves the following basic steps:
1. Creating classes that define object 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.
A Message for an object is a request for execution of a procedure, and therefore will invoke a
function (procedure) in the receiving object that generates the desired results. Message passing
involves specifying the name of object, the name of the function (message) and the information
to be sent. Example:
Employee. Salary (name);

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

C++ (C with Classes)

1. C++ Development started in 1979.

2. During the creation of Ph.D. thesis, Bjarne Stroustrup worked with language called Simula,

which is basically useful for the simulation work.

3. Simula was first language to support object-oriented programming paradigm

4. Bjarne Stroustrup identified that this OOP features can be included in the software

development.

5. After that Bjarne Stroustrup started working on the C language and added more extra OOP

features to the classic C.

6. He added features in such a fashion that the basic flavor of C remains unaffected.

7. C++ includes some add-on features such as classes, basic inheritance, in-lining, default
function arguments, and strong type checking

There are several versions of C++ Programming Language –

1. Visual C++

2. Borland C++

3. Turbo C++
4. Standardize C++ [ANSI C++]

Structure of C++ Program: Layout of C++ Program

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43
First C++ Program

Printing a String
#include<iostream>
using namespace std;
int main()
{
cout<<” c++ is better than c \n”;
return 0;
}

Program feature
Like C, the C++ program is a collection of function. The above example contain only one
function main(). As usual execution begins at main(). Every C++ program must have a main().
C++ is a free form language. With a few exception, the compiler ignore carriage return and white
spaces. Like C, the C++ statements terminate with semicolons.

Comments
Single line comment

// This is an example of
// C++ program to illustrate
// some of its features

Multiline comments

/* This is an example of
C++ program to illustrate
some of its features
*/

Output operator

Cout<<”C++ is better than C.”;

Causes the string in quotation marks to be displayed on the screen. This statement introduces two
new C++ features, cout and <<.

The identifier cout(pronounced as C out) is a predefined object that represents the standard output
stream in C++. Here, the standard output stream represents the screen. The operator << is called
the insertion or put to operator.

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

The iostream File

We have used the following #include directive in the program:


#include <iostream>

The #include directive instructs the compiler to include the contents of the file enclosed within
angular brackets into the source file. The header file iostream.h should be included at the
beginning of all programs that use input/output statements.

Namespace

Namespace is a new concept introduced by the ANSI C++ standards committee. This defines a
scope for the identifiers that are used in a program. For using the identifier defined in the
namespace scope we must include the using directive, like

using namespace std;

Here, std is the namespace where ANSI C++ standard class libraries are defined. All ANSI C++
programs must include this directive. This will bring all the identifiers defined in std to the current
global scope. Using and namespace are the new keyword of C++.

Return Type of main()


In C++, main () returns an integer value to the operating system. Therefore, every main () in C++
should end with a return (0) statement;

AVERAGE OF TWO NUMBERS

#include<iostream.h> // include header file


Using namespace std;

int main()
{
float number1, number2,sum, average;
cin >> number1; // Read Numbers
cin >> number2; // from keyboard
sum = number1 + number2;
average = sum/2;
cout << ”Sum = “ << sum << endl;
cout << “Average = “ << average << “\n”;
return 0;
} //end of example

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

The output would be:


Enter two numbers: 6.5 7.5
Sum = 14
Average = 7

Input Operator
The statement, cin >> number1;
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 (pronounced ‘C in’) is a predefined object in C++ that corresponds to the
standard input stream. Here, this stream represents the keyboard.
The operator >> is known as extraction or get from operator. It extracts (or takes) the value from
the keyboard and assigns it to the variable on its right.

Cascading of I/O Operators

We have used the insertion operator << repeatedly in the last two statements for printing results.
The statement

Cout << “Sum = “ << sum << endl;

First sends the string “Sum = “ to cout and then sends the value of sum. Finally, it sends the newline
character so that the next output will be in the new line. The multiple use of << in one statement
is called cascading.

Using the cascading technique, the last two statements can be combined as follows:
Cout << “Sum = “ << sum << endl;
<< “Average = “ << average << endl;

This is one statement but provides two line of output. If you want only one line of output, the statement
will be:
Cout << “Sum = “ << sum << “,”
<< “Average = “ << average << endl;

The output will be:


Sum = 14, average = 7

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

We can also cascade input operator >> as shown below:

Cin >> number1 >> number2;

The values are assigned from left to right. That is, if we key in two values, say, 10 and 20, then 10 will
be assigned to munber1 and 20 to number2.

Storage Classes in C++ **


A storage class defines the scope (visibility) and life-time of variables and/or functions within a
C++ Program. These specifiers precede the type that they modify. There are following storage
classes, which can be used in a C++ Program

auto

register

static

extern

The auto Storage Class

The auto storage class is the default storage class for all local variables.

{
int mount;
auto int month;
}
The example above defines two variables with the same storage class, auto can only be used within
functions, i.e., local variables.

The register Storage Class

The register storage class is used to define local variables that should be stored in a register instead
of RAM. This means that the variable has a maximum size equal to the register size (usually one
word) and can't have the unary '&' operator applied to it (as it does not have a memory location).

{
register int miles;
}
The register should only be used for variables that require quick access such as counters.

The static Storage Class

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

The static storage class instructs the compiler to keep a local variable in existence during the life-
time of the program instead of creating and destroying it each time it comes into and goes out of
scope. Therefore, making local variables static allows them to maintain their values between
function calls.

The static modifier may also be applied to global variables. When this is done, it causes that
variable's scope to be restricted to the file in which it is declared.

In C++, when static is used on a class data member, it causes only one copy of that member to be
shared by all objects of its class.

#include <iostream>

// Function declaration
void func(void);

static int count = 10; /* Global variable */

main() {
while(count--) {
func();
}
return 0;
}

// Function definition
void func( void ) {
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
}

When the above code is compiled and executed, it produces the following result:

i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0

The extern Storage Class

The extern storage class is used to give a reference of a global variable that is visible to ALL the
program files. When you use 'extern' the variable cannot be initialized as all it does is point the
variable name at a storage location that has been previously defined.

When you have multiple files and you define a global variable or function, which will be used in
other files also, then extern will be used in another file to give reference of defined variable or
function. Just for understanding extern is used to declare a global variable or function in another
file.

The extern modifier is most commonly used when there are two or more files sharing the same
global variables or functions as explained below.

First File: main.cpp

#include <iostream>

int count ;
extern void write_extern();

main() {
count = 5;
write_extern();
}

Second File: support.cpp

#include <iostream>

extern int count;

void write_extern(void) {
std::cout << "Count is " << count << std::endl;
}

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

Here, extern keyword is being used to declare count in another file. Now compile these two files
as follows:

$g++ main.cpp support.cpp -o write

This will produce write executable program, try to execute write and check the result as follows:

$./write
5

Inline Functions **
C++ provides inline functions to help reduce function call overhead—especially for small
functions. Placing the qualifier inline before a function’s return type in the function definition
“advises” the compiler to generate a copy of the function’s code in place (when appropriate) to
avoid a function call.

The trade-off is that multiple copies of the function code are inserted in the program (often making
the program larger) rather than there being a single copy of the function to which control is passed
each time the function is called. The compiler can ignore the inline qualifier and typically does so
for all but the smallest functions.

// inline function that calculates the volume of a cube.


#include <iostream>
using std::cout;
using std::cin;
using std::endl;

// Definition of inline function cube. Definition of function appears


// before function is called, so a function prototype is not required.
// First line of function definition acts as the prototype.

inline double cube( const double side )


{
return side * side * side; // calculate the cube of side
} // end function cube

int main()
{
double sideValue; // stores value entered by user

for ( int i = 1; i <= 3; i++ )


{
cout << "\nEnter the side length of your cube: ";
cin >> sideValue; // read value from user

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

// calculate cube of sideValue and display result


cout << "Volume of cube with side "
<< sideValue << " is " << << endl;
}
} // end main

Output:
Enter the side length of your cube: 1.0
Volume of cube with side 1 is 1
Enter the side length of your cube: 2.3
Volume of cube with side 2.3 is 12.167
Enter the side length of your cube: 5.4
Volume of cube with side 5.4 is 157.464

References and Reference Parameters **


Two ways to pass arguments to functions in many programming languages are pass-by value and
pass-by-address. When an argument is passed by value, a copy of the argument’s value is made
and passed (on the function call stack) to the called function. Changes to the copy do not affect the
original variable’s value in the caller.

Reference Parameters

With pass-by-reference, the caller gives the called function the ability to access the caller’s data
directly, and to modify that data if the called function chooses to do so.

A reference parameter is an alias for its corresponding argument in a function call.

For example, the following declaration in a function header

int &count

when read from right to left is pronounced “count is a reference to an int.”

// ref.cpp, Example for Pass-by-Reference


// Comparing pass-by-value and pass-by-reference with references.

#include <iostream>
using namespace std;

int squareByValue( int ); // function prototype (value pass)

void squareByReference( int & ); // function prototype (reference pass)

int main()

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

{
int x = 2; // value to square using squareByValue
int z = 4; // value to square using squareByReference

// demonstrate squareByValue
cout << "x = " << x << “before squareByValue\n";
cout << "Value returned by squareByValue: "<< squareByValue( x )<<endl;
cout << "x = " << x << " after squareByValue\n" << endl;

// demonstrate squareByReference
cout << "z = " << z << “ before squareByReference" << endl;
squareByReference( z );
cout << "z = " << z << " after squareByReference" << endl;

} // end main

// squareByValue multiplies number by itself, stores the


// result in number and returns the new value of number
int squareByValue( int number )
{
return number *= number; // caller's argument not modified
} // end function squareByValue

// squareByReference multiplies numberRef by itself and stores the result


// in the variable to which numberRef refers in the caller
void squareByReference( int &numberRef )
{
numberRef *= numberRef; // caller's argument modified
} // end function squareByReference

Output

x = 2 before squareByValue
Value returned by squareByValue: 4
x = 2 after squareByValue
z = 4 before squareByReference
z = 16 after squareByReference

References as Aliases within a Function

int count = 1; // declare integer variable count

int &cRef = count; // create cRef as an alias for count

cRef++; // increment count (using its alias cRef)

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

// ref1.cpp. Example for Reference variable


// initializing and using a reference.
#include <iostream>
using namespace std;

int main()
{
int x = 3;

int &y = x; // y refers to (is an alias for) x

cout << "x = " << x << endl << "y = " << y << endl;
y = 7; // actually modifies x
cout << "x = " << x << endl << "y = " << y << endl;

} // end main

Output

x=3
y=3
x=7
y=7

Initializing and using a reference.

// Ref2.cpp, Example for uninitialized Reference variable


// uninitialized reference is a syntax error.

#include <iostream>
using namespace std;

int main()
{
int x = 3;

int &y; // Error: y must be initialized


cout << "x = " << x << endl << "y = " << y << endl;
y = 7;
cout << "x = " << x << endl << "y = " << y << endl;

} // end main

Output

C:\examples\ch1 \Ref2.cpp(10) : error C2530: 'y' : references must be initialized

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

Returning a Reference from a Function

Returning references from functions can be dangerous. When returning a reference to a variable
declared in the called function, the variable should be declared static within that function.
Otherwise, the reference refers to an automatic variable that is discarded when the function
terminates; such a variable is “undefined,” and the program’s behavior is unpredictable.
References to undefined variables are called dangling references.

Default Arguments **
When a program omits an argument for a parameter with a default argument in a function call, the
compiler rewrites the function call and inserts the default value of that argument to be passed as
an argument in the function call.

1. Default arguments must be the rightmost (trailing) arguments in a function’s


parameter list. When calling a function with two or more default arguments, if an omitted
argument is not the rightmost argument in the argument list, then all arguments to the right
of that argument also must be omitted.

2. Default arguments should be specified with the first occurrence of the function
name—typically, in the function prototype. If the function prototype is omitted because
the function definition also serves as the prototype, then the default arguments should be
specified in the function header.

3. Default values can be any expression, including constants, global variables or function
calls.

4. Default arguments also can be used with inline functions.

// Using default arguments, example program


#include <iostream>
using namespace std;

// function prototype that specifies default arguments


int boxVolume( int length = 1, int width = 1, int height = 1 );

int main()
{
// no arguments--use default values for all dimensions
cout << "The default box volume is: " << boxVolume() ;

// specify length; default width and height

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

cout << "\n\nThe volume of a box with length 10,\n" << "width 1 and height 1 is: " <<
boxVolume( 10 );

// specify length and width; default height


cout << "\n\nThe volume of a box with length 10,\n" << "width 5 and height 1 is: " <<
boxVolume( 10, 5 );

// specify all arguments


cout << "\n\nThe volume of a box with length 10,\n" << "width 5 and height 2 is: " << boxVolume(
10, 5, 2 )<< endl;

} // end main

// function boxVolume calculates the volume of a box


int boxVolume( int length, int width, int height )
{
return length * width * height;

} // end function boxVolume

Output

The default box volume is: 1

The volume of a box with length 10,


width 1 and height 1 is: 10

The volume of a box with length 10,


width 5 and height 1 is: 50

The volume of a box with length 10,


width 5 and height 2 is: 100

Unary Scope Resolution Operator

1. It’s possible to declare local and global variables of the same name. This causes the global
variable to be “hidden” by the local variable in the local scope. C++ provides the scope
resolution operator (::) to access a global variable when a local variable of the same name
is in scope.

2. The unary scope resolution operator cannot be used to access a local variable of the same
name in an outer block.

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

3. A global variable can be accessed directly without the unary scope resolution operator if
the name of the global variable is not the same as that of a local variable in scope.

// sro.cpp, example for Scope Resolution Operator


// using the unary scope resolution operator.

#include <iostream>
using namespace std;

int number = 7; // global variable named number

int main()
{

double number = 10.5; // local variable named number

// display values of local and global variables

cout << "Local double value of number = " <<number << "\n Global int value of number
= " << ::number << endl;

} // end main

Output

Local double value of number = 10.5


Global int value of number = 7

Function Overloading **
C++ enables several functions of the same name to be defined, as long as these functions have
different sets of parameters (at least as far as the parameter types or the number of parameters or
the order of the parameter types are concerned). This capability is called function overloading.

When an overloaded function is called, the C++ compiler selects the proper function by examining
the number, types and order of the arguments in the call.

Function overloading is commonly used to create several functions of the same name that perform
similar tasks, but on data of different types.
For example, many functions in the math library are overloaded for different numeric data types.

Overloaded square Functions

// overloading.cpp

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

// Overloaded square functions.


#include <iostream>
using namespace std;

// function square for int values


int square( int x )
{
cout << "square of integer " << x << " is ";
return x * x;
} // end function square with int argument

// function square for double values


double square( double y )
{
cout << "square of double " << y << " is ";
return y * y;
} // end function square with double argument

int main()
{
cout << square( 7 ); // calls int version
cout << endl;
cout << square( 7.5 ); // calls double version
cout << endl;
} // end main

Output

square of integer 7 is 49
square of double 7.5 is 56.25

How the Compiler Differentiates Overloaded Functions


Overloaded functions are distinguished by their signatures—a combination of a function’s name
and its parameter types (in order).

The compiler encodes each function identifier with the number and types of its parameters
(sometimes referred to as name mangling or name decoration) to enable type-safe linkage. This
ensures that the proper overloaded function is called and that the argument types conform to the
parameter types.

Overloaded functions can have different return types, but if they do, they must also have different
parameter lists. Again, you cannot have two functions with the same signature and different return
types.

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

Static Binding: By default, matching of function call with the correct function definition
happens at compile time. This is called static binding or early binding or compile-time binding.
Static binding is achieved using function overloading and operator overloading. Even though
there are two or more functions with same name, compiler uniquely identifies each function
depending on the parameters passed to those functions.

Dynamic Binding**

In OOPs Dynamic Binding refers to linking a procedure call to the code that will be executed only
at run time. The code associated with the procedure in not known until the program is executed,
which is also known as late binding.

Example :

#include <iostream.h>
int Square(int x)
{ return x*x; }

int Cube(int x)
{ return x*x*x; }

int main()
{
int x =10;
int choice;
do
{
cout << "Enter 0 for square value, 1 for cube value: ";
cin >> choice;
} while (choice < 0 || choice > 1);

int (*ptr) (int); switch (choice)


{
case 0: ptr = Square; break;
case 1: ptr = Cube; break;
} cout << "The result is: " << ptr(x) << endl;

return 0;
}

Output:

Enter 0 for square value, 1 for cube value:0


The result is:100

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

In the above OOPs example the functions "Square" and "Cube" are called only at runtime based
on the value given for "choice". Then a pointer "ptr" is used to call the appropriate function to get
the result.

Data types

#include <iostream>
using namespace std;

int main() {
cout << "Size of char is " << sizeof(char) << endl;
cout << "Size of int is " << sizeof(int) << endl;
cout << "Size of float is " << sizeof(float) << endl;
cout << "Size of short int is " << sizeof(short int) << endl;
cout << "Size of long int is " << sizeof(long int) << endl;
cout << "Size of double is " << sizeof(double) << endl;
cout << "Size of wchar_t is " << sizeof(wchar_t) << endl;
return 0;
}

C++ Enumeration (enum)

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43
An enumeration is a user-defined data type that consists of integral constants. To define an enumeration,
keyword enum is used.

enum season { spring, summer, autumn, winter };

Here, the name of the enumeration is season.

And, spring, summer and winter are values of type season.

By default, spring is 0, summer is 1 and so on. You can change the default value of an enum
element during declaration (if necessary).

enum season

{ spring = 0,

summer = 4,

autumn = 8,

winter = 12

};

Enumerated Type Declaration

When you create an enumerated type, only blueprint for the variable is created. Here's how you
can create variables of enum type.

enum boolean { false, true };

// inside function

enum boolean check;

Here, a variable check of type enum boolean is created.

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

Here is another way to declare same check variable using different syntax.

enum boolean

false, true

} check;

Example 1: Enumeration Type


#include <iostream>
using namespace std;

enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

int main()
{
week today;
today = Wednesday;
cout << "Day " << today+1;
return 0;
}

Output

Day 4

Example2: Changing Default Value of Enums


#include <iostream>
using namespace std;

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32};

int main() {

seasons s;

s = summer;
cout << "Summer = " << s << endl;

return 0;
}

Output

Summer = 4

Why enums are used in C++ programming?

An enum variable takes only one value out of many possible values. Example to demonstrate it,

#include <iostream>
using namespace std;

enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3
} card;

int main()
{

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

card = club;
cout << "Size of enum variable " << sizeof(card) << " bytes.";
return 0;
}

Output

Size of enum variable 4 bytes.

It's because the size of an integer is 4 bytes.

Strings
C++ provides following two types of string representations:

1. The C-style character string

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

char greeting[] = "Hello";

#include <iostream>

using namespace std;

int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: ";


cout << greeting << endl;

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

return 0;
}

String Functions

S.N. Function & Purpose

1 strcpy(s1, s2);

Copies string s2 into string s1.

2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3 strlen(s1);
Returns the length of string s1.

4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.

Following example makes use of few of the above-mentioned functions:

#include <iostream>
#include <cstring>

using namespace std;

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

int main () {
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;

// copy str1 into str3


strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation


len = strlen(str1);
cout << "strlen(str1) : " << len << endl;

return 0;
}

Output:

strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10

2. The string class type introduced with Standard C++.

The standard C++ library provides a string class type that supports all the operations mentioned
above, additionally much more functionality.

#include <iostream>
#include <string>

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

using namespace std;

int main () {
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;

// copy str1 into str3


str3 = str1;
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;

// total lenghth of str3 after concatenation


len = str3.size();
cout << "str3.size() : " << len << endl;

return 0;
}

When the above code is compiled and executed, it produces result something as follows:

str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10

C++ Pointers

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

A pointer is a variable whose value is the address of another variable. Like any variable or
constant, you must declare a pointer before you can work with it. The general form of a pointer
variable declaration is:

type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of
the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use
for multiplication. However, in this statement the asterisk is being used to designate a variable as
a pointer. Following are the valid pointer declaration:

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is
the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the pointer
points to.

Using Pointers in C++:


There are few important operations, which we will do with the pointers very frequently. (a) we
define a pointer variables (b) assign the address of a variable to a pointer and (c) finally access
the value at the address available in the pointer variable. This is done by using unary
operator * that returns the value of the variable located at the address specified by its operand.
Following example makes use of these operations:

#include <iostream>

using namespace std;

int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

Muralidhara S, AP, Dept.of CSE


Object oriented programming with C++ 16CSE43

cout << "Value of var variable: ";


cout << var << endl;

// print the address stored in ip pointer variable


cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}

output:

Value of var variable: 20


Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

Read:
Control Structure: if-else, switch with examples
Loops: while, do-while, for with examples
Arrays declaration and initialization examples
Functions- categories with examples

Muralidhara S, AP, Dept.of CSE

Potrebbero piacerti anche