[go: up one dir, main page]

0% found this document useful (0 votes)
4 views9 pages

Unit I

The document provides an overview of Procedure Oriented Programming (POP) and Object Oriented Programming (OOP) languages, detailing their characteristics, advantages, and key concepts such as functions, classes, inheritance, and polymorphism. It discusses the evolution from machine-level languages to high-level languages, emphasizing the modularity and data encapsulation in OOP. Additionally, it introduces C++ as an OOP language, explaining basic syntax and structure for writing programs.

Uploaded by

shashankgujrati1
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)
4 views9 pages

Unit I

The document provides an overview of Procedure Oriented Programming (POP) and Object Oriented Programming (OOP) languages, detailing their characteristics, advantages, and key concepts such as functions, classes, inheritance, and polymorphism. It discusses the evolution from machine-level languages to high-level languages, emphasizing the modularity and data encapsulation in OOP. Additionally, it introduces C++ as an OOP language, explaining basic syntax and structure for writing programs.

Uploaded by

shashankgujrati1
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/ 9

UNIT I

Procedure Oriented Programming Language

Introduction:
Programmers write instructions in various programming languages to perform their computation In the procedure oriented approach, the problem is viewed as sequence of things to be done such as
tasks suchas: reading , calculation and printing.
(i) Machine levelLanguage
Procedure oriented programming basically consist of writing a list of instruction or actions for the
(ii) Assembly levelLanguage
computer to follow and organizing these instruction into groups known as functions.
(iii) High levelLanguage

Machine level Language :


Machine code or machine language is a set of instructions executed directly by a computer's central
Main program
processing unit (CPU). Each instruction performs a very specific task, such as a load, a jump, or an
ALU operation on a unit of data in a CPU register or memory. Every program directly executed by a
CPU is made up of a series of such instructions. Function-2 Function-3
Function-1
Assembly level Language :
An assembly language (or assembler language) is a low-level programming language for a computer,
or other programmable device, in which there is a very strong (generally one-to-one) correspondence
between the language and the architecture's machine code instructions. Assembly language is The disadvantage of the procedure oriented programming languages is:
1. Global dataaccess
converted into executable machine code by a utility program referred to as an assembler; the 2. It does not model real word problem verywell
conversion process is referred to as assembly, or assembling the code. 3. No datahiding

High level Language :


High-level language is any programming language that enables development of a program in much Global data Global data
simpler programming context and is generally independent of the computer's hardware architecture.
High-level language has a higher level of abstraction from the computer, and focuses more on the
Function-1 Function-3
programming logic rather than the underlying hardware components such as memory addressing and
register utilization. Function-2

Local data Local data Local data


The first high-level programming languages were designed in the 1950s. Now there are dozens of
different languages, including Ada , Algol, BASIC, COBOL, C, C++, JAVA, FORTRAN, LISP,
Pascal, and Prolog. Such languages are considered high-level because they are closer to human Characteristics of procedure oriented programming:
languages and farther from machine languages. In contrast, assembly languages are considered low-
level because they are very close to machine languages. 1. Emphasis is on doingthings(algorithm)
2. Large programs are divided into smaller programs known asfunctions.
The high-level programming languages are broadly categorized in to two programming paradigms: 3. Most of the functions share globaldata
4. Data move openly around the system from function to function
(iv) Procedure oriented programming(POP)language. 5. Function transforms data from one form toanother.
(v) Object oriented programming(OOP)language. 6. Employs top-down approach in programdesign

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

Object Oriented Programing BASIC CONCEPTS OF OBJECTS ORIENTED PROGRAMMING

“Object oriented programming as an approach that provides a way of modularizing programs by


creating partitioned memory area for both data and functions that can be used as templates for 1. Objects
creating copies of such modules on demand”. 2. Classes
3. Data abstraction and encapsulation
Object A ObjectB 4. Inheritance
5. Polymorphism
6. Dynamic binding
Data Data 7. Message passing

Communication
OBJECTS
Functions Functions
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 must handle.

Object C The fundamental idea behind object oriented approach is to combine both data and function into a
single unit and these units are called objects.
Functions The term objects means a combination of data and program that represent some real word entity. For
example: consider an example named Amit; Amit is 25 years old and his salary is 2500. The Amit
may be represented in a computer program as an object. The data part of the object would be (name:
Amit, age: 25, salary:2500)
Data
The program part of the object may be collection of programs (retrive of data, change age, change of
salary). In general even any user –defined type-such as employee may be used. In the Amit object
Features of the Object Oriented programming the name, age and salary are called attributes of theobject.

1. Emphasis is on doing rather thanprocedure.


2. programs are divided into what are known asobjects. Object: Student STUDENT
3. Data structures are designed such that they characterize theobjects.
4. Functions that operate on the data of an object are tied together in the data DATA Total
structure. Name
5. Data is hidden and can‟t be accessed by externalfunctions. Date-of-birth
6. Objects may communicate with each other throughfunctions. Marks A verage
7. New data and functions can be easilyadded.
8. Follows bottom-up approach in program design. FUNCTIONS
Total
Average D isplay
Display

CLASS:

A group of objects that share common properties for data part and some program part are collectively
called as class.

In C ++ a class is a new data type that contains member variables and member functions that operate on
the variables.
By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)
DATA ABSTRACTION :
Abstraction refers to the act of representing essential features without including the back ground BENEFITS OF OOP:
details or explanations. Classes use the concept of abstraction and are defined as size, width and cost
and functions to operate on the attributes. OOP offers several benefits to both the program designer and the user. Object-oriented contributes to
the solution of many problems associated with the development and quality of software products.
DATA ENCAPSALATION : The principal advantages are:
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 1. Through inheritance we can eliminate redundant code and extend the use of existing
can access it. These functions provide the interface between the objects data and the program. classes.
2. We can build programs from the standard working modules that communicate with one
INHERITENCE : another, rather than having to start writing the code from scratch. This leads to saving of
development time and higherproductivity.
Inheritance is the process by which objects of one class acquire the properties of another class. In the 3. This principle of data hiding helps the programmer to build secure programs that can‟t be
concept of inheritance provides the idea of reusablity. This mean that we can add additional features invaded by code in other parts of theprogram.
to an existing class with out modifying it. This is possible by desining a new class will have the
4. It is possible to have multiple instances of an object to co-exist with out anyinterference.
combined features of both theclasses.
5. It is easy to partition the work in a project based onobjects.
6. Object-oriented systems can be easily upgraded from small to largesystems.
POLYMORPHISIM: 7. Message passing techniques for communication between objects makes the interface
Polymorphism means the ability to take more than one form. An operation may exhibit different description with external systems muchsimpler.
instance. The behaviour depends upon the type of data used in the operation. 8. Software complexity can be easilymanaged.
A language feature that allows a function or operator to be given more than one definition. The types
of the arguments with which the function or operator is called determines which definition will be APPLICATION OF OOP:
used.
Overloading may be operator overloading or function overloading. The most popular application of oops up to now, has been in the area of user interface design such as
windows. There are hundreds of windowing systems developed using oop techniques.
It is able to express the operation of addition by a single operater say „+‟. When this is possible you
use the expression x + y to denote the sum of x and y, for many different types of x and y; integers , Real business systems are often much more complex and contain many more objects with complicated
float and complex no. You can even define the + operation for two strings to mean the concatenation attributes and methods. Oop is useful in this type of applications because it can simplify a complex
of the strings. problem. The promising areas for application of oop includes.

DYNAMIC BINDING : 1. Real – Timesystems.


Binding refers to the linking of a procedure call to the code to the executed in response to the call. 2. Simulation andmodeling
Dynamic binding means the code associated with a given procedure call is not known untill the time 3. Object orienteddatabases.
of the call at run-time. It is associated with a polymorphic reference depends upon the dynamic type 4. Hypertext,hypermedia andexpertext.
of that reference. 5. Al and expertsystems.
6. Neural networks and parallelprogramming.
7. Dicision support and office automationsystems.
MESSAGE PASSING : 8. CIM / CAM / CADsystem.
An object oriented program consists of a set of objects that communicate with each other.
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 result. Message passing involves
specifying the name of the object, the name of the function (message) and information to be sent.

Employee . Salary(name)

Object Information
Message

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

Cascading Of I/O Operator:


Basics of C++
C ++ is an object oriented programming language, C ++ was developed by Jarney Stroustrup at AT & T cout<<”sum=”<<sum<<”\n”;
Bell lab, USA in early eighties. C ++ was developed from c and simula 67 language. C ++ was early cout<<”sum=”<<sum<<”\n”<<”average=”<<average<<”\n”;
called „C with classes‟. cin>>number1>>number2;

C++ Comments:
Structure Of A Program :
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 Probably the best way to start learning a programming language is by writing a program. Therefore,
the end of line is ignored. Note that there is no closing symbol. here is our first program:
The double slash comment is basically a single line comment. Multi line comments can be written as // my first program in C++
follows:
#include <iostream>
// this is an example of using namespace std;
// c++ program
// thank you int main ()
The c comment symbols /* ….*/ are still valid and more suitable for multi line comments. {
cout << "Hello World!";
/* this is an example of c++ program */ return 0;
}
Output Operator: Output:-Hello World!

The statement cout <<”Hello, world” displayed the string with in quotes on the screen. The identifier The first panel shows the source code for our first program. The second one shows the result of the
cout can be used to display individual characters, strings and even numbers. It is a predefined object program once compiled and executed. The way to edit and compile a program depends on the
that corresponds to the standard output stream. Stream just refers to a flow of data and the standard compiler you are using. Depending on whether it has a Development Interface or not and on its
Output stream normally flows to the screen display. The cout object, whose properties are defined in version. Consult the compilers section and the manual or help included with your compiler if you
iostream.h represents that stream. The insertion operator << also called the „put to‟ operator directs have doubts on how to compile a C++ console program.
the information on its right to the object on its left. 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
Return Statement: 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 justwritten:
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. // 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
Input Operator:
explanations or observations within the source code itself. In this case, the line is a brief description
of what our program is.
The statement
cin>> number 1; #include <iostream>
is an input statement and causes. The program to wait for the user to type in a number. The number Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code
keyed in is placed in the variable number1. The identifier cin is a predefined object in C++ that lines with expressions but indications for the compiler's preprocessor. In this case the directive
corresponds to the standard input stream. Here this stream represents the key board. #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
The operator >>is known as get from operator. It extracts value from the keyboard and assigns it to included because its functionality is going to be used later in the program.
the variable on itsright.
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 ()
By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)
This line corresponds to the beginning of the definition of the main function. The main function is return 0;
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 All in just one line and this would have had exactly the same meaning as the previous code.
after it – the instructions contained within this function's definition will always be the first ones to be In C++, the separation between statements is specified with an ending semicolon (;) at the end of
executed in any C++ program. For that same reason, it is essential that all C++ programs have a main each one, so the separation in different code lines does not matter at all for this purpose. We can
function. write many statements per line or write a single statement that takes many code lines. The division of
The word main is followed in the code by a pair of parentheses (()). That is because it is a function code in different lines serves only to make it more legible and schematic for the humans that may
declaration: In C++, what differentiates a function declaration from other types of expressions are read it.
these parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters
within them. Let us add an additional instruction to our first program:
Right after these parentheses we can find the body of the main function enclosed in braces ({}). // my second program in C++
What is contained within these braces is what the function does when it isexecuted. #include <iostream>
using namespace std;
cout << "Hello World!";
This line is a C++ statement. A statement is a simple or compound expression that can actually int main ()
produce some effect. In fact, this statement performs the only action that generates a visible effect in {
our first program. cout << "Hello World! ";
cout represents the standard output stream in C++, and the meaning of the entire statement is to cout << "I'm a C++ program";
insert a sequence of characters (in this case the Hello World sequence of characters) into the standard return 0;
output stream (which usually is thescreen). }
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 Output:-Hello World! I'm a C++ program
our code.
Notice that the statement ends with a semicolon character (;). This character is used to mark the end In this case, we performed two insertions into cout in two different statements. Once again, the
of the statement and in fact it must be included at the end of all expression statements in all C++ separation in different lines of code has been done just to give greater readability to the program,
programs (one of the most common syntax errors is indeed to forget to include some semicolon after since main could have been perfectly valid defined this way:
a statement). int main ()
{
return 0; cout << " Hello World! ";
The return statement causes the main function to finish. return may be followed by a return code (in cout << " I'm a C++ program ";
our example is followed by the return code 0). A return code of 0 for the main function is generally return 0;
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 We were also free to divide the code into more lines if we considered it more convenient:
executed. There were lines containing only comments (those beginning by //). There were lines with int main ()
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 cout <<"Hello World!"; cout
the insertion into cout), which were all included within the block delimited by the braces ({}) of the << "I'm a C++program";
main function. return0;
}
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, insteadof
And the result would again have been exactly the same as in the previous examples.
int main () 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
cout << " Hello World!";
themselves. Preprocessor directives must be specified in their own line and do not have to end with a
return 0;
semicolon (;).
}

We could have written: STRUCTURE OF C++ PROGRAM

int main ()  Include files


{  Class declaration
cout << "Hello World!";  Class functions, definition
By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

 Main function program


KEYWORDS:
Example :-

# include<iostream.h> 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
class person keywords not found in ANSI C are shown in red letter.
{
char name[30];
C++ KEYWORDS:
int age;
public:
void getdata(void); Asm double new switch
void display(void);
}; Auto else operator template

Break enum private this


void person :: getdata ( void )
{ Case extern protected throw
cout<<”enter name”;
cin>>name; Catch float public try
cout<<”enter age”;
cin>>age; Char for register typedef
}
Class friend return union
void display()
{ Const goto short unsigned
cout<<”\n name:”<<name;
cout<<”\n age:”<<age; Continue if signed virtual
}
Default inline sizeof void
int main( ) Delete long struet while
{

person p;
p.getdata(); IDENTIFIERS:
p.display();
return(0); Identifiers refers to the name of variable , functions, array, class etc. created by programmer. Each
language has its own rule for naming the identifiers.
} The following rules are common for both C and C++.
1. Only alphabetic chars, digits and under score arepermitted.
2. The name can‟t start with adigit.
TOKENS: 3. Upper case and lower case letters aredistinct.
The smallest individual units in program are known as tokens. C++ has the following 4. A declared keyword can‟t be used as a variablename.
tokens.
In ANSI C the maximum length of a variable is 32 chars but in c++ there is no bar.
i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)
BASIC DATA TYPES IN C++ long int 4 -2147483648 to 2147483648

signed long int 4 -2147483648 to 2147483648


C ++ Data Types
unsigned long int 4 0 to 4294967295

Built in types Derived type float 4 3.4E-38 to 3.4E+38


User defined type Array
Structure Function double 8 1.7E -308 to 1.7E +308
Union pointer
Class long double 10 3.4E-4932 to 1.1E+ 4932
enumeration

void The type void normally used for:

1) To specify the return type of function when it is not returning anyvalue.


Integral type Floating point 2) To indicate an empty argument list to afunction.

Example:

Void function(void);
int char float double
Another interesting use of void is in the declaration of genetic pointer

Example:

Both C and C++ compilers support all the built in types. With the exception of void the basic Void *gp;
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. Assigning any pointer type to a void pointer without using a cast is allowed in both C and ANSI C.
However the modifier long may also be applied to double. 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++.

Data types in C++ can be classified under various categories. Example:

TYPE BYTES RANGE void *ptr1;

char 1 -128 to – 127 void *ptr2;

usigned 1 0 to 265 Are valid statement in ANSI C but not in C++. We need to use a cast operator.

sgned char 1 -128 to 127 ptr2=(char * ) ptr1;

int 2 -32768 to 32768

unsigned int 2 0 to 65535 USER DEFINED DATA TYPES:

singed int 2 -32768 to 32768 STRUCTERS AND CLASSES


short int 2 -32768 to 32768
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

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

another user defined data type known as class which can be used just like any other basic data type to C++ also permits the creation of anonymous enums ( i.e, enums without tag names)
declare a variable. The class variables are known as objects, which are the central focus of oops.
Example:
ENUMERATED DATA TYPE:
An enumerated data type is another user defined type which provides a way for attaching names to enum{off,on};
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 Here off is 0 and on is 1.these constants may be referenced in the same manner as regular constants.
alternative means for creating symbolic.
Example:
Example:
int switch-1=off;
enum shape {circle,square,triangle}
int switch-2=on;
enum colour{red,blue,green,yellow}
ANSI C permits an enum defined with in a structure or a class, but the enum is globally visible. In
enum position{off,on} C++ an enum defined with in a class is local to that class.

The enumerated data types differ slightly in C++ when compared with ANSI C. In C++, the tag SYMBOLIC CONSTANT:
names shape, colour, and position become new type names. That means we can declare new
variables using the tag names. There are two ways of creating symbolic constants in c++.
Example: 1. using the qualifier const.
2. defining a set of integer constants using enum keywords.
Shape ellipse;//ellipse is of type shape
In both C and C++, any value declared as const can‟t be modified by the program in any way.
colour background ; // back ground is of type colour In C++, we can use const in a constant expression. Such as

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. const int size = 10 ;
char name (size) ;
Example:

colour background =blue; //vaid 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.
colour background =7; //error in c++
const size=10;
colour background =(colour) 7;//ok
Means
How ever an enumerated value can be used in place of an int value.
const int size =10;
Example:
C++ requires a const to be initialized. ANSI C does not require an initializer, if none is given, it initializes
int c=red ;//valid, colour type promoted to int the const to 0.
In C++const values are local and in ANSIC const values are global. However they can be made local made
By default, the enumerators are assigned integer values starting with 0 for the first enumerator, 1 for local by declaring them as static. In C++ if we want to make const value as global then declare as extern
the second and so on. We can also write storage class.
enum color {red, blue=4,green=8};
Ex: external consttotal=100; Another method
enum color {red=5,blue,green}; of naming integer constants is as follows:-
enum {x,y,z};

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)
DECLARATION OF VARIABLES:
In ANSIC C all the variable which is to be used in programs must be declared at the beginning of the OPERATORS IN C++ :
program.ButinC++wecandeclarethevariablesanywhoseintheprogramwhere it requires. This makes the C++ has a rich set of operators. All C operators are valid in C++ also. In addition. C++ introduces some
program much easier to write and reduces the errors that may be caused by having to scan back and forth. It new operators.
also makes the programeasier to understand because the variables are declared in the context of their use.
<< insertion operator

>> extraction operator


Example:
main() :: scope resolution operator
{
float x,average; ::* pointer to member declarator
float sum=0;
for(int i=1;i<5;i++) * pointer to member operator
{
cin>>x; .* pointer to member operator
sum=sum+x
} Delete memory release operator
float average;
average=sum/x; Endl line feed operator
cout<<average;
} New memory allocation operator

Setw field width operator

REFERENCE VARIABLES: SCOPE RESOLUTION OPERATOR:

C++interfaces a new kind of variable known as the reference variable. A references variable provides an Like C, C++ is also a block-structured language. Blocks and scopes can be used in constructing
alias.(alternative name) for a previously defined variable. For example ,if we make the variable sum a programs. We know same variables can be declared in different blocks because the variables declared in
reference to the variable total, then sum and total can be used interchangeably to represent the variable. blocks are local to that function.
Blocks in C++ are often
A reference variable is created as follows: nested. Example:
Synatx: Datatype & reference –name=variable name; ----------------
----------------
Example: float total=1500; {
float &sum=total; Int x =10;
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. Intx=1; Block2
Example: --------------- Block1
int n[10]; ---------------
int &x=n[10]; }
char &a=’\n’; ----------------
----------------

}
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.

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

In C, the global version of a variable can't be accessed from with in the inner block. C++ resolves this *q=7.5;
problem by introducing a new operator :: called the scope resolution operator .This can be used to uncover a Assign 25 to the newly created int object and 7.5 to the float object. We can also initialize the memory
hidden variable. using the new operator.

Syntax: : : variable–name; Syntax:


int *p=ne\v int(25);
Example: float *q =new float(7.5);
#include <iostrcam.h> new can be used to create a memory space for any data type including user defined such as
int m=10; arrays,structures,andclasses.Thegeneralformforaone-dimensionalarrayis:
main()
{ pointer-variable =new data types [size];
int m=20;
creates a memory space for an array of 10 integers.
{
int k=m;
If a data object is no longer needed, it is destroyed to release the memory space for
int m=30;
reuse.
cout<<”weareininnerblock”;
cout<<"k="<<k<<endl;
cout<<"m="<<m<<endl; Syntax: delete pointer-variable;
cout<<":: m="<<::m<<endl;
Example:
}
delete p;
cout<<”\nweareinouterblock\n”; delete q;
cout<<"m="<<m<<endl;
cout<<":: m="<<::m<<endl;
} If we want to free a dynamically allocated array ,we must use the following
form ofdelete.

delete [size] pointer-variable;


or
Memory Management Operator
delete [ ] pointer variable;
C uses malloc and calloc functions to allocate memory dynamically at run time. Similarly it uses the functions
Free()to free dynamically allocated memory. We use dynamic allocation techniques when it is not known in
advance how much of memory space as needed. MANIPULATERS:

C++ also support those functions it also defines two unary operators new and delete that perform the task Manipulators are operator that are used to format the data display. The most commonly manipulators are
of allocating and freeing the memory in a better and easier way. endl and setw.
The endl manipulator, when used in an output statement, causes a line feed to be insert.(just like \n)
The new operator can be used to create objects of any type.
Example:
Syntax: cout<<”m=”<<m<<endl;
cout<<”n=”<<n<<endl;
pointer- variable =new datatype; cout<<”p=”<<p<<endl;
Ifweassumethevaluesofthevariablesas2597,14and175respectively
Example: m=2597; n=14;
p=new int; q=new int; p=175
Where p is a pointer of type int and q is a pointer of type float. Itwaswanttoprint allnosinright justifiedwayusesetwwhichspecifyacommonfieldwidth for all
int *p=new int; thenos.

float *p=newfloat; Example: cout<<setw(5)<<sum<<endl;


cout<<setw(10)<<”basic”<<setw(10<<basic<<endl;
Subsequently, the statements Cout<<setw(10)<<”allowance”<<setw(10<<allowance<<endl;
cout<<setw(10)<<”total=”<<setw(10)<<total;
*p=25;
By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)
Switch(expr)

CONTROL STRUCTURES: {

Like c, c++, supports all the basic control structures and implements them various control statements. case 1:

The if statement: action1;

The if statement is impklemented in two forms: break;

1. simple if statement case 2:


2. if… else statement
action2;
Simple if statement:
break;
if (condition)
..
{
..
Action;
default:
}
message
If.. else statement
}
If (condition)

Statment1
The while
Else
statement:
Statement2
While(condition)

{
The switch statement
Stements
This is a multiple-branching statement where, based on a condition, the control is transferred to one of the many
possible points; }

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

The do-while statement: INLINE FUNCTION:

Syn: To eliminate the cost of calls to small functions C++ proposes a new feature called inline function.
An inline function is a function that is expanded inline when it is invoked .That is the compiler
do replaces the function call with the corresponding function code.
The inline functions are defined as follows:-
{
inline function-header
Stements {
function body;
} while(condition); }
Example: inline double cube (doublea)
The for loop: {
return(a*a*a);
for(expression1;expression2;expression3) }
The above inline function can be invoked by statements like
{ c=cube(3.0);
d=cube(2.5+1.5);
Statements; remember that the inline keyword merely sends a request, not a command to the complier. The
compiler may ignore this request if the function definition is too long or too complicated and compile
the function as a normal function.
Statements;
.
} CLASS:-
Class is a group of objects that share common properties and relationships .In C++, a class is a new
FUNCTION IN C++ : data type that contains member variables and member functions that operates on the variables. A
class is defined with the keyword class. It allows the data to be hidden, if necessary from external use.
The main( ) Functon ; When we defining a class, we are creating a new abstract data type that can be treated like any other
built in datatype.
Generally a class specification has two parts:-
ANSI does not specify any return type for the main ( ) function which is the starting point for the execution of a a) Class declaration
program . The definition of main( ) is :- b) Class function definition
the class declaration describes the type and scope of its members. The class function
main() definition describes how the class functions are implemented.
{
//main program statements
} Syntax:-
class class-name
This is property valid because the main() in ANSIC does not return any value. In C++, the main() returns a value {
of type int to the operating system.The functions that have a return value should use the return statement for private:
terminating. The main()function in C++ is therefore defined as follows. variable declarations;
function declaration ;
public:
int main( ) variable declarations;
{ function declaration;
-------------- };
-------------- The members that have been declared as private can be accessed only from with in the class. On the
return(0) other hand , public members can be accessed from outside the class also. The data hiding is the key
} feature of oops. The use of keywords private is optional by default, the members of a class are private.
Since the return type of functions is int by default, the key word int in the main( ) header is optional. The variables declared inside the class are known as data members and the functions are known as
members mid the functions. Only the member functions can have access to the private data members and
private functions. However, the public members can be accessed from the outside the class. The binding
of data and functions together into a single class type variable is referred to as encapsulation.

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)
Syntax:-
class item CREATING OBJECTS:
{ Once a class has been declared we can create variables of that type
int member; by using the classname.
float cost; Example:
public: item x;
void getldata (int a ,float b); creates a variables x of type item. In C++, the class variables are known as objects. Therefore
void putdata (void); x is called an object of type item.
The class item contains two data members and two function members, the data
members are private by default while both the functions are public by declaration. The function
getdata() can be used to assign values to the member variables member and cost, and putdata() for
displaying their values . These functions provide the only access to the data members from outside item x, y ,z also possible.
the class. class item
{
-----------
-----------
-----------
}x ,y ,z;
would create the objects x ,y ,z of type item.

ACCESSING CLASS MEMBER:


The private data of a class can be accessed only through the member functions of that
class. The main() cannot contains statements that the access number and cost directly.
Syntax:
object name.function-name(actualarguments);
Example:- x.getdata(100,75.5);
It assigns value 100 to number, and 75.5 to cost of the object x by
implementing the getdata() function .
similarly the statement
x. putdata ( ); //would display the values of data members.
x. number = 100 is illegal .Although x is an object of the type item to which number belongs ,
the number can be accessed only through a member function and not by the objectdirectly.
Example:
class xyz
{
Intx;
Inty;
public:
intz;
};
---------
----------
xyz p;
p.x=0; error . x isprivate
p,z=10; ok ,z ispublic

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

INSIDE THE CLASS DEF1NATION:


Another method of defining a member function is to replace thefunction declaration by the
actual function definition inside the class.
DEFINING MEMBER FUNCTION:
Example:
Member can be defined in two places
class item
• Outside the class definition
{
• Inside the classfunction
Intnumber;
float cost;
public:
void getdata (int a ,float b);
OUTSIDE THE CLASS DEFlNAT1ON;
void putdata(void)
{
Member function that are declared inside a class have to be defined separately cout<<number<<endl; cout<<cost<<endl;
outside the class.Their definition are very much like the normal functions. }
};
An important difference between a member function and a normal
function is that a member function incorporates a membership.Identify label in the header. The A C++ PROGRAM WITHCLASS:
„label‟ tells the compiler which class the function belongs to. # include< iostream. h>
class item
Syntax: {
int number;
return type class-name::function-name(argument declaration ) float cost;
{ public:
function-body void getdata ( int a , float b);
} void putdala ( void)
The member ship label class-name :: tells the compiler that the function function - {
name belongs to the class class-name . That is the scope of the function is restricted to the class- cout<<“number:”<<number<<endl;
name specified in the header line. The :: symbol is called scope resolutionoperator. cout<<”cost :”<<cost<<endl;
}
Example: };
void item :: getdata (int a , float b ) void item :: getdata (int a , float b)
{ {
number=a; number=a;
cost=b; cost=b;
} }
void item :: putdata ( void) main ( )
{ {
cout<<”number=:”<<number<<endl; item x;
cout<<”cost=”<<cost<<endl; cout<<”\nobjectx”<<endl;
} x. getdata( 100,299.95);
The member function have some special characteristics that are often used in the program x .putdata();
development. item y;
• Several different classes can use the same functionname.The "membership label" cout<<”\n object y”<<endl;
willresolvetheirscope,memberfunctionscanaccesstheprivatedataoftheclass y. getdata(200,175.5);
.A non member function can't do so. y. putdata();
• A member function can call another member function directly, without using the dot }
operator.
Output: object x
number100

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)
cost=299.950012
object -4
cost=175.5 NESTING OF MEMBER FUNCTION;

A member function can be called by using its name inside another member function of the
same class. This is known as nesting of member functions.
Q.
Write a simple program using class in C++ to input subject mark and printsit. #include <iostream.h>
ans: class set
class marks {
{ int m,n;
private : public:
int ml,m2; void input(void);
public: void display (void);
void getdata(); void largest(void);
void displaydata(); };
}; int set::largest (void)
void marks: :getdata() {
{ if(m>n)
cout<<”enter 1st subject mark:”; return m;
cin>>ml; else
cout<<”enter 2nd subject mark:”; return n;
cin>>m2; }
} voidset::input(void)
void marks: :displaydata() {
{ cout<<”input values of m and n:”;
cout<<”Ist subject mark:”<<ml<<endl ; cin>>m>>n;
cout<<”2nd subject mark:”<<m2; }
} void set::display(void)
voidmain() {
{ cout<<”largestvalue=”<<largest()<<”\n”;
clrscr(); }
marks x; void main()
x.getdata(); {
x.displaydata(); set A;
A.input( );
} A.display( );
}

output:

Input values of m and n:

3017

largest value= 30

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

#include<iostream.h>
class part
Private member functions:
{
private:
Although it is a normal practice to place all the data items in a private section and all the functions in intmodelnum,partnum;
public, some situations may require contain functions to be hidden from the outside calls. Tasks such float cost;
public:
as deleting an account in a customer file or providing increment to and employee are events of void setpart ( int mn, int pn ,float c)
serious consequences and therefore the functions handling such tasks should have restricted access. {
modelmim=mn;
We can place these functions in the privatesection. partnum=pn;
cost=e;
}
void showpart ( )
A private member function can only be called by another function that is a member of its class. Even {
Cout<<endl<<”model:”<<modelnum<<end1;
an object can not invoke a private function using the dot operator. Cout<<”num:”<< partnum <<endl
Cout<<”cost:”<<”$”<cost;
}
};
Class sample void main()
{
{ part pl,p2;
intm; p1.setpart(644,73,217.55);
p2.setpart(567,89,789.55);
void read (void); pl.showpart();
void write (void); pl.showpart();
}
};
if si is an object of sample, then output:- model:644
s.read(); num:73
is illegal. How ever the function read() can be called by the function update ( ) to cost: $217550003
update the value of m. model: 567
void sample :: update(void) num:89
{ cost: $759.549988
read( );
}

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)
#indude<iostream.h>
Class distance
{
ARRAY WITH CLASSES:
private:
int feet;
floatinches; #include<iostream.h>
public: #include<conio.h>
void setdist ( int ft, float in)
{ class employee
feet=ft; {
inches=in;
} private:
void getdist() char name[20];
{
cout<<”enter feet:”; int age,sal;
cin>>feet; public:
cout<<”enter inches:”; void getdata();
cin>>inches;
} void putdata();
void showdist() };
{
cout<< feet<<”_”inches«endl; void employee : : getdata ()
} {
};
void main( ) cout<<”enter name :”;
{ cin>>name;
distance dl,d2;
d1.setdist(1 1,6.25); cout<<”enter age :”;
d2.getdata(); cin>>age;
cout<<endl<<”dist:”<<d 1 .showdist();
cout<<”\n”<<”dist2:”; cout<<”enter salary:”;
d2.showdist(); cin>>sal;
}
return(0);
output:- enter feet: 12 }
enter inches:6.25 void employee : : putdata ( )
dist 1:”11‟-6.1.5” {
dist 2: 12‟-6.25” cout<<name <<endl;
cout<<age<<endl;
cout<<sal<<endl;
return(0);
}
intmain()
{

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

cin>>sal;
}
employee emp[5]:
void emp :: putdata()
for( int i=0;i<5;i++)
{
{ cout<<”emp name:”<<name<<endl;
emp[i].getdata();
cout<<”emp age:”<<age<<endl;
}
cout<<”emp salary:”<<sal;
cout<<endl;
}
for(i=0;i<5;i++)
{
void main()
emp[i].putdata();
{
}
emp foreman[5];
getch();
emp engineer[5];
return(0);
for(int i=0;i<5;i ++)
}
{
cout<<” for foreman:”;
ARRAY OF OBJECTS:- foreman[i] . getdata();
#include<iostream.h>
}
#include<conio.h>
cout<<endl;
class emp
for(i=0;i<5;i++)
{
{
private:
Foreman[i].putdata(); .
char name[20];
}
int age,sal;
for(int i=0;i<5;i ++)
public:
{
void getdata( );
cout<<” for engineer:”;
void putdata( );
ingineer[i].getdata();
};
}
void emp : : getdata()
for(i=0;i<5;i++)
{
{
coul<<”enter empname”: .
ingineer[i].putdata();
cin>>name;
}
cout<<”enter age:”<<endl;
getch();
cin>>age;
return(0)
cout<<”enter salun :”;
}

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) 41 P.T.O

You might also like