0% found this document useful (0 votes)
9 views

C++ programming Concept

C++ programming Concept

Uploaded by

bikash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

C++ programming Concept

C++ programming Concept

Uploaded by

bikash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

C++ programming Concept

Kashiram Pokharel
Syllabus:
Introduction:
• C++, It is an extension to C language and was developed by Bjarne
stroustrup at bell labs.
• C++ is a statically typed, compiled, general purpose, case -
sensitive,Highlevel free-form programming language that supports
procedural, object-oriented, and generic programming.
• C++ is an object-oriented programming language but is not purely
Object Oriented. Its features like Friend and Virtual, violate some of
the very important OOPS features
• which gives a clear structure to programs and allows code to be
reused.
Feature of c++
• Namespace
• The namespace is used for logical grouping of program element like
variables,classes.functions etc.
• helps to localize a name of identifiers so that there is no naming conflict across
different modules designed by different members of programming team
• Class
• A class is a collection of objects sharing common properties and relationship. It is a
user defined data type and behave like built-in type of programming language
• class specifies what data and what functions will be included in object of that class
• Inheritance
• Inheritance is a mechanism in which new class can be created with the help of
existing class.
• The existing class is called parent class and new class is called derived class, the
derived class holds the new feature as well as some feature of parent class.
Feature of c++
• Access controllers/visibility levels/visibility mode/access identifiers:
• The private ,public and protected keyword are used for access control of members within
class .
• The members declared as private are hidden from other part of the program and are visible
by the member functions with in the class only.
• The public access specifier allows functions or data members in public section to be
accessible to other part of the program too.
• The data member protected in a class makes function or data member accessible from the
function of the derived class too.
• constructor and destructor:
• A constructor is a special member function of a class whose task is to allocate the required
memory for members as well as initialize the objects of it’s class.
• when an object is no longar needed it can be destroyed by a special member function called
destructor
• Friend function and Friend class:
• nonmember function can’t access the private member of a class from outside the class.
• using friend function we can access even the private member of a class.To access all hidden
member of a class by another class,the class as a whole can be declared as friend.
Feature of c++
• Reference variable:
• A reference variable is an alternative name(or alias )for a variable .It is useful for
passing argument by reference that makes the programing easier.
• Function overloading:
• define same function name for different operation, is called function overloading.
• Type of polymorphism.
• operator overloading:
• The process of making an operator to exhibit different behaviour in different instance
is known as operator overloading.
• For example the operator “+” can be used to perform the additional operation on
user derined data such as string concatnation,complex number addition.
Feature of c++
• Exceptional handling:
• Exception are errors that may occur at runtime.Exception handling can be
used to support ideas of error handling and fault tolerant computing
• Inline function:
• To save the execution time for small functins.we can put the code of function
body directly in the line of called location.
• In each function call the codes in the called function get iserted at the line of
the call instead of jumping from calling function to called function and back to
calling function again.this type of function whose code is copied in the code
location is called inline function
Type conversion

• When writing an expression, we use different type of data and when


evaluating expressions with such mixed data types, we must have
knowledge of converting one type of data into another type.
• There are two way of data conversion
• Implicit (automatic) type conversion
• Explicit (type cast) type conversion
Implicit type conversion:

• Implicit conversions do not require any operator. They are automatically


performed when a value is copied to a compatible type.
• For example:
short a=2000;
int b;
b=a;
• Here, the value of a has been promoted from short to int and we have not had to specify any
type-casting operator. This is known as a standard conversion
• Standard conversions affect fundamental data types, and allow conversions such as
the conversions between numerical types (short to int, int to float, double to int...),
to or from bool, and some pointer conversions.
• This can be avoided with an explicit conversion.
• Implicit conversions also include constructor or operator conversions, which affect
classes that include specific Constructors or operator functions to perform
conversions.
Implicit type conversion:
For example:
class A • 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
class B condition type conversion (type promotion)
{ takes place to avoid lose of data.
public: • All the data types of the variables are upgraded
B (A a) { to the data type of the variable with largest
data type.
}
};
A a;
B b=a;
Here, a implicit conversion happened between objects of class A and class B,
because B has a constructor that takes an object of class A as parameter.
Therefore implicit conversions from A to B are allowed.
Implicit type conversion:

• The automatic type conversion can be divided into two


categories.
• Promotion
• When two operands of different types are encountered in the same expression,
the lower type variable is converted to the type of the higher type
variable by the compiler automatically. This is also called type promotion. The
order of types is given below:
• when we try to evaluate two or more data of different type, then one type
should converted to higher type before final result is calculated
int a;
float b;
a+b; //here a is automatically converted into floating point.
• bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long ->
float -> double -> long double
Demotion.

• When two operands of different types are encountered in the same


expression, the higher type variable is converted to the type of
the lower type variable by the compiler with some warning. This is
called type Demotion.
• Some of these conversions may imply a loss of precision, which the
compiler can signal with a warning.
Explicit type conversion:
• method for the programmer to change or cast a value from one data type to
another; called explicit type conversion.
• Converting an expression of a given type into another type is known as type-
casting.
• general syntax is
data_type (expression);
Example
float (10)/float (3);
• Besides these two type castings, C++ also has four operators for type conversion.
They are known as type conversion operators. They are:
• static_cast
• dynamic_cast
• const_cast
• reinterpret_cast
Dynamic Memory Allocation:
• If the amount of memory required is unknown at compile time, the
memory allocation can be performed during execution. Such a
technique of allocating memory during runtime on demand is known
as dynamic memory allocation.
• In c++ dynamic memory allocation is perform with new and delete
operator.
new operator:

• The new operator is used to dynamic memory allocation similar to the


standard library function malloc(), calloc()
• The new operator reserves memory at runtime from the memory heap
form the operating system. and returns the address of the obtained
memory.
• The memory reserved by the new in any scope remains as it is even
after the program control goes out of the scope, so if we allocate
memory dynamically in any function the allocated memory can used
even if the function returns.
• The general syntax of using new operator is :
• data_type *pointer_variable;
• pointer_variable=new data_type; //It allocates single variable
program using new operator.

#include<iostream.h>
#include<conio.h>
void main() Example:
{ • pointer_variable= new data_type[size];
int n,c,*p; for example:
cout<<”enter an integer”; • int *ptr;
cin>>n; • ptr=new int;
p=new int[n]; • ptr=new int[10];
cout<<”enter “<<n<<”integer:” ;
for(c=0;c<n;c++)
{
cin>>p[c];
}
cout<<”elements entered are”
for(c=0;c<n;c++)
{
cout<<p[c]<<endl;
}
delete[]p;
getch();
}
delete operator:

• The delete operator is used to release the memory allocated by the


new operaror back to the operating system memory pool.
• The memory release by the delete operator can be reused in other
parts of the program.
• The delete operator destroy the dynamic variable created at the
runtime using new operator.
• The general format of using delete operator is:
• delete pointer_variable;
• In case of array:
• delete [ ] pointer_variable;
program using delete operator.
void main()
{
int n,i,*ptr, tot=0; Example:
float avg;
cout<<”how many numbers”; • In c++ we use new and delete operator to
allocate and free the memory in a better and
cin>>n; easy way.
ptr=new int[n]; • If we allocate a fixed size for our data. This size
for(i=0;i<n;i++) can't be increased or decreased while execution
{ of the program. We can't change it even if the
size allocated is more or less than our
cout<<”enter number”; requirement. This type of allocation of memory is
cin>>ptr[i]; called Static Memory Allocation. This leads to
} wastage or shortage of memory.
for(i=0;i<n;i++) • Dynamic memory allocation allows you to
{ manually handle memory space for your
program.
tot+=ptr[i];
}
avg=float(tot)/n;
cout<<”Total number=”<<tot<<endl;
cout<<”average=”<<avg<<endl”
delete []ptr;
getch();
}
Manipulator:
• The manipulators in C++ are special functions that can be used with insertion (<<) and
extraction (>>) operators to manipulate or format the data in the desired way.
• These are non printing statement of functions which only modifies the I/O stream but does
not change the value of a variable.
• It is mainly used to make up the program structure. Which are generally defined in
<iomanip.h> header file.
• Manipulators are operators used in C++ for formatting output. i.e. The manipulators are
used to set field widths, set precision, inserting a new line, skipping white space etc.
• Manipulator can be divided into two parts
1. Non-argument manipulators (Without Parameters)
• Non-argument manipulators are also known as “non-Parameterized manipulators”.
• These manipulators require iostream header.
• Examples are endl, fixed, showpoint, left and flush.
2. Argumented manipulators (With parameters)
• Argument manipulators are also known as “Non parameterized manipulators”.
• These manipulators require iomanip header.
• Examples are setprecision, setw and setfill.
Manipulators without arguments:
• The most important manipulators defined by the IOStream library are provided below.
• endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e. it forces all the output
written on the screen or in the file) the output stream.
• cout << endl;
• ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.
cout << "Please, enter some whitespaces followed by a sentence:\n";
cin >> ws;
cin.getline (str1,256);
cout << "Please, enter some whitespaces followed by a sentence:\n";
ws (cin);
cin.getline (str2,256);
• ends: It is also defined in ostream and it inserts a null character into the output stream.
• It typically works with std::ostrstream, when the associated output buffer needs to be null-terminated to be processed as a C string.
cout << "a";
cout << "b" << ends;
cout << "c" << endl;

• flush: The flush function removes all data from the output stream. It’s an output manipulator
• cout.flush();
Manipulator with arguments:
• setw (int n) – To set field width to n
• stprecision (int p) – The precision is fixed to p
• setfill (Char f) – To set the character to be filled
• setbase(base n)-Changes base to n, where n is 10, 8, or 16. (Anything
else results in 0.) If n is zero, output is base 10
constant
• Constants is a value that can be stored in a memory and can’t change during
execution of the memory.
• Constants are also called literals, are the actual representation of values used in
the program. There are five types of constants
• Numeric constants
• Integer constants
• Decimal constants
• Hexadecimal constants
• Octal constants
• Floating point constants
• Character constants
• String constants
• Enumerated constants.
Numeric constants:

• Numeric constants are numeric digits which may or may not have decimal points. The rules for
defining numeric constants are
• Comma and blank space can’t be included with in the constants. Numeric constants can either be
positive or negative but default sign is always positive.
• The numeric constants can be divided into two parts
• Integer constants:
o Integer constant are numeric representation that doesn’t contain fractional part.
o The integer constants may be positive or negative numbers without fractional part.
o There are three type of integer constants.
• Decimal constants:
Decimal numbers are the integer numbers represented with base 10 number system. Point or comma is not
allowed in decimal number system. For example: 65, +45, -66 etc.
• Hexadecimal integer constant:
Hexadecimal numbers are the integer numbers that have base sixteen. These numbers use digits from 0 to 9 and
alphabets A to F(or a to f).Hexadecimal numbers are written using ox before hexadecimal digits.
• Octal integer constants:
These are the integer number that have base eight. These number use digits form 0 to 7. Octal numbers are written
using o before the octal digits. For example 023, 054
Numeric constant
• Integer and floating point constants represent numbers. They are
often referred to collectively as numeric _ type constants.
• The following rules apply to all numeric type constants.
• Commas and blank spaces cannot be included within the constants.
• The constant can be preceded by a minus (-) if desired. The minus sign is an
operator that changes the sign of a positive constant though it can be thought
of as a part of the constant itself.
• The value of a constant cannot exceed specified minimum and maximum
bounds.
Integer constant:
• An integer constant is an integer-valued number. Thus it consists of a sequence of digits.
• Integer (number) constants can be written in three different number systems:
• decimal(base 10),
• octal (base 8) and
• Hexadecimal (base 16).
• A decimal integer constant can consists of any combination of digits taken from the set 0
through 9. If the constant contains two or more digits, the first digit must be something
other than 0. Several valid decimal integer constants are shown below:
0 1 143 5280 are valid decimal constant and
• some invalid decimal integer constant are:
• 12,452 Illegal character (,)
• 36.0 Illegal character (.)
• 10 20 30 Illegal character (blank space)
• 123-45-6743 Illegal character (-)
• 0900 The first digit cannot be zero.
Octal and Hexadecimal constant
• An octal integer constant can consist of any combination of digits taken from the set 0 through 7. However,
the first digit must be 0, in order to identify the constant as an octal number.
• Valid octal number (integer) constants are shown below:
0 01 0743 07777
• The following octal integer constants are written incorrectly for the reason stated:
• 0743 Does not begin with 0.
• 5280 Illegal character (8)
• 777.777 Illegal character (.)
• A hexadecimal integer constant must begin with either 0x or 0X. It can then be followed by any combination
of digits taken from the sets 0 through 9 and a through f (either upper or lower case).
• The letters a through f (or A through F) represent the (decimal) quantities 10 through 15 respectively.
• Several valid hexadecimal integer constants are shown below:
0x 0X1 0X7FFF 0xabcd
• The following hexadecimal integer constants are written incorrectly for the reason stated:
• 0X12.34 Illegal character (.)
• 013E38 doesn’t begin with 0x or 0X.
• 0x.4bff Illegal character (.)
• 0XDEFG Illegal character (G)
floating point constants:
• Floating point are numeric representation that contain fractional form or exponential form.
• The floating point value can be represented into two part integer part and fractional or
separated by dot.
• Floating-point constants have a "mantissa," which specifies the value of the number, an
"exponent," which specifies the magnitude of the number, and an optional suffix that
specifies the constant's type(double or float
• No commas are allowed in floating point number and It have much greater range than
integer constants.
• Several valid floating point constants
• 0. 1. 0.2 827.602
• 500. 0.000743 12.3
• 2E.8 0.006e.3 1.6667e+8
• The following are not valid floating point constants for the reason stated. 1 Either a decimal
point or an exponent must be present.
• 1,000.0 Illegal character (,)
• 2E+10.2 The exponent must be an integer (it cannot contain a decimal point)
• 3E 10 Illegal character (blank space) in the exponent.
Character constant:
• Character constants are one or more members of the “source character set,” the character set in
which a program is written, surrounded by single quotation marks (').
• They are used to represent characters in the “execution character set,” the character set on the
machine where the program executes.
• A character constant is a single character, enclosed in apostrophes (i.e. single quotation marks).
• Several character constants are shown below:
‘A’ ‘X’ ‘3’ ‘?’ ‘ ´
• Character constants have integer values that are determined by the computer’s particular
character set. Thus, the value of a character constant may vary from one computer to another.
• The constants themselves, however, are independent of the character set. This feature eliminates
the dependence of a C program on a particular character set.
• Most computers, and virtually all personal computer make use of ASCII (i.e. American Standard
Code for Information Interchange) character set, in which each individual character is numerically
encoded with its own unique 7-bit combination (hence a total of 27=128 difference characters).
String constant:
• A string consists of any number of consecutive characters (including
none), enclosed in (double) quotation marks.
• Several string constants are shown below:
• “green”
• “Washington D.C. 2005”
Enumeration
• An enumerated data type is another user-defined type which provides a way for
attacking names to numbers, thereby, increasing comprehensibility of the code.
• The enum keyword automatically enumerates a list of words by assigning them
values 0, 1, 2 and so on.
• This facility provides an alternative means of creating symbolic constants. Eg.
enum shape {circle, square, triangle} ;
enum color {red, blue, green, yellow} ;
enum position {off, on} ;
• In C++, the tag names shape, color, and position becomes new type names. By
using these tag names, we can declare new variables. Examples:
shape ellipse ; // ellipse is of type shape
color background ; // background is of type color
• Each enumerated data type retains its own separate. This means that C++
doesn’t permit an int value to be automatically converted to an enum
value. e.g.
color background = blue ; // allowed
color background = 7 ; // Error in C++
color background = color(7) ; // ok
• By default, the enumerators are assigned integers values starting with 0 for
the first enumerator, 1 for the second and so on. e.g.
enum color(red, blue = 4, green=8) ;
enum color(red=5, blue, green) ; are valid definitions.
• In first case, red is 0 by default.
• On second case, blue is 6 and green is 7. Note that the subsequent
initialized enumerators are larger by one than their predecessors.
Thank You.

You might also like