0% found this document useful (0 votes)
8 views14 pages

C++ Chapter1

Contains short detailed notes of c++ chapter 1

Uploaded by

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

C++ Chapter1

Contains short detailed notes of c++ chapter 1

Uploaded by

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

CHAPTER -1

Software Evolution
Ernest Tello, a well-known writer in the field of artificial intelligence, compared
the evolution of software technology to the growth of a tree. Like a tree, the
software evolution has had distinct phase or “layer” of growth. These layers
were built up one by one over the last five decades with each layer representing
an improvement over the previous one.
Since the invention of the computer, may programming approaches have been
tried. These include techniques such as modular programming, top-down
programming, bottom-up programming and structured programming. The
primary motivation in each has been the concern to handle the increasing
complexity of programs that are reliable and maintainable. These techniques
have become popular among programmers over the last two decades.

Aspect Machine Assembly Procedure Object


Language Language Oriented Oriented
Programming Programming
Definition The lowest- A low-level A programming A programming
level programming paradigm that paradigm that
programming language that focuses on uses objects and
language, uses symbolic functions or classes to
consisting of instructions procedures to structure code,
binary code which are operate on data. focusing on data
that the translated into and methods.
computer’s machine code
CPU can
execute
directly
Level Low-Level Low-Level High-Level High-Level
Readability Not readable More readable Readable; Readable;
by humans; than machine structured with organized around
consists of code; uses clear procedural objects and
binary (0s and mnemonics and flow. classes.
1s) symbols.
Abstraction No abstraction; Minimal Moderate High abstraction;
Level directly abstraction; abstraction; encapsulates data
interacts with closer to focuses on and behavior
hardware hardware than procedures and within objects
high-level routines.
languages
Ease of Use Very difficult; Difficult; Easier compared Easier to manage
requires required to low level and understand
detailed understanding languages; uses complex systems
knowledge of of assembly high level due to
hardware. syntax and construct encapsualtion
CPU
architecture
Error Minimal to Minimal; Better error Advanced error
Handling none; error requires handling through handling through
handling is manual structured exception
difficult checking and control flow. mechanism
debugging
Maintenance Difficult; Difficult; Easier; changes Easier; changes
changes require changes need are localized to can be made in
significant careful procedure one place and
effort handling of low reflected
level throughout the
instructions program
Execution Very fast; runs Fast; Direct Generally fast; May be slower
Speed directly on the translation to depends on the due to
hardware machine code efficiency of the abstraction
procedures. layers, but
optimization
techniques can
mitigate this.
Code None; code is Low; code is Moderate; High; classes
Reusability highly specific specific to the functions ca be and objects can
to particular hardware and reused but not in be reused across
tasks task a structured different
manner programs and
modules.
Examples Binary code Assembly code Language like C, Language like
like 10101000 like MOV Pascal C++, Java,
AX,1 Python

What is C++?
The predecessor of C++ is C, which was designed by Dennis Richie at Bell
Labs and first released in 1973. C is a widely used language and was used to
write the early versions of Unix and Windows. Indeed, the libraries and
software-development libraries of many operating systems are still written to
have C interfaces. C is powerful because it can be used to write code that is
compiled to a compact form, it uses a static type system (so the compiler does
the work of type checking), and the types and structures of the language allow
for direct memory access to computer architecture.

C++ is an object-oriented programming language. It was developed by Bjarne


Stroustrup at AT&T bell laboratories in Murray Hill, New Jersey, USA, in the
early 1980’s. Stoustrup, an admirer of simula67 and a strong supporter of C,
wanted to combine the best of both the languages and create a more powerful
language that could support object-oriented programming features and still
retain the power and elegance of C.
Therefore, C++ is an extension of C with a major addition to the original C
language, Stroustrup initially called the new language C with classes. However,
later in 1983, the name was changed to C++.
During the early 1990’s the language underwent a number of improvement and
changes. In November 1997, the ANSI/ISO standards committee standardised
these changes and added several new features to the language specifications. C+
+ is a superset of C.

Object-Oriented Language
Object-Oriented programming is not the right any particular language. Like
structured programming, OOP concept can be implemented using the language
such as C and Pascal.
The language should support several of the OOP concepts to claims that they
are object-oriented. Depending upon the feature they support, they can be
classified into the following two categories :
1. Object-based Programming language and
2. Object- oriented programming languages

Object-based Programming is the style of programming that primarily


supports encapsulation and object identity. Major features that are
required for object-based programming are:
a) Data Encapsulation
b) Data hiding and access mechanisms
c) Automatic initialization and clear-up of objects
d) Operator Overloading
Data Encapsulation
Data encapsulation is a fundamental principle in Object-Oriented Programming
(OOP) that refers to the bundling of data and methods that operate on that data
within a single unit, typically an object or class. This approach hides the internal
state of the object from the outside world and only exposes a controlled
interface for interacting with that data. By encapsulating data, an object’s
implementation details are hidden, which means that the internal workings of
the object can be changed without affecting code that uses the object.
Encapsulation promotes modularity, enhances maintainability, and helps in
protecting the integrity of the data by preventing unintended interference.
Data Hiding and Access Mechanisms
Data hiding is a technique used to protect an object’s internal state by making
its data members inaccessible from outside the object. In OOP, this is typically
achieved through access modifiers such as private, protected, and
public. These modifiers control the visibility of data members and methods.
For example, data members marked as private can only be accessed and
modified by methods within the same class, whereas those marked as public
can be accessed by any code. Access mechanisms, like getter and setter
methods, provide controlled access to the private data, allowing it to be read or
modified in a controlled manner, which helps maintain the integrity and
consistency of the data.
Automatic Initialization and Clear-Up of Objects
Automatic initialization and clear-up of objects are managed by the constructor
and destructor in object-oriented programming languages. The constructor is a
special method that is automatically invoked when an object is created,
initializing the object’s data members and setting up necessary resources.
Conversely, the destructor is a method that is automatically called when an
object is destroyed, ensuring that any resources allocated by the object (such as
memory or file handles) are properly released. This automatic management
simplifies resource handling and helps prevent memory leaks or resource
conflicts, making the code more reliable and easier to maintain.
Operator Overloading
Operator overloading is a feature in OOP that allows programmers to define
custom behaviors for operators (such as +, -, *, /) when they are applied to
objects of user-defined classes. This means that operators can be customized to
perform operations that are meaningful for the class. For example, in a class
representing complex numbers, the + operator can be overloaded to add two
complex numbers together according to the rules of complex arithmetic.
Operator overloading enhances the readability and usability of the code by
allowing natural expressions and operations to be performed on objects, as if
they were built-in types. However, it should be used judiciously to ensure that
the code remains intuitive and clear.
Object-Oriented Programming incorporated all of object -based programming
features along with two additional features, namely, inheritance and dynamic
binding. Object-oriented programming can therefore be characterized by the
following statement:
Object-based features+ Inheritance+ Dynamic Binding
Inheritance
Inheritance is a mechanism that allows one class (known as a subclass or
derived class) to inherit properties and behaviors from another class (known as a
superclass or base class). This creates a hierarchical relationship between
classes, where the subclass inherits data members and methods from the
superclass, enabling it to reuse and extend the functionality of the existing code.
Inheritance promotes code reuse and helps in organizing code in a more logical
manner. For instance, if you have a base class Vehicle with common attributes
like speed and fuel, and derived classes like Car and Bike that add specific
features, the derived classes can reuse and extend the base class’s functionality
without having to rewrite it.
Dynamic Binding
Dynamic binding, also known as late binding, refers to the process of
determining which method or function to invoke at runtime rather than compile
time. This is crucial in OOP when dealing with inheritance and polymorphism.
With dynamic binding, a program can decide at runtime which implementation
of an overridden method to execute based on the actual object type that is being
referenced. For example, if a method drive() is overridden in both the Car and
Bike subclasses, dynamic binding ensures that the appropriate drive() method is
called depending on whether the object is of type Car or Bike, even if the
reference is of type Vehicle. This flexibility allows for more generic code and
supports polymorphism, where a single interface can be used to represent
different underlying forms (objects).
Polymorphism
Polymorphism is a core concept in Object-Oriented Programming (OOP) that
allows objects of different classes to be treated as objects of a common base
class, primarily through function or method overriding. In C++, polymorphism
is achieved through both compile-time (static) and runtime (dynamic)
mechanisms. Here’s a detailed explanation of how polymorphism is
implemented in C++:
1. Compile-Time Polymorphism
Compile-time polymorphism, also known as static polymorphism, is achieved
through function overloading and operator overloading. This type of
polymorphism is resolved during compile time.
 Function Overloading: Allows multiple functions with the same name
but different parameters to exist in the same scope. The correct function is
selected based on the number and type of arguments.
 Operator Overloading: Allows operators to be redefined for user-
defined types. This enables operators like +, -, *, etc., to work with class
objects.
2. Runtime Polymorphism
Runtime polymorphism, or dynamic polymorphism, is achieved through
inheritance and virtual functions. This type of polymorphism is resolved during
runtime.
 Base Class and Derived Class: To achieve runtime polymorphism, a
base class must declare a function as virtual, and the derived class can
override this function.
 Virtual Destructors: When using polymorphism, especially when
deleting objects through base class pointers, it is essential to declare
destructors as virtual in the base class to ensure proper cleanup of derived
class resources.

Objects
Objects are the basic run-time entities in an object-oriented system. They may
represent a person, place, a bank account , a table of data or any items that rhe
program has to handle. They may also represent user-defined data such as
vectors, time and lists. Programming problem is analyzed in terms of objects
and the nature of communication between them. Program objects should be
chosen such that they match closely with the real-world objects.
When a program is executed, the object interact by sending messages to one
another.
Example – If “customer” and “account” are two objects in a program, then the
customer object mat send a message to the account object requesting for the
bank balance. Each object contains data, and code to manipulate the data.
Objects can interact without having to know the details of each other’s data or
code.

Classes
The entire set of data and code of an object can be made a user-defined data
types with the help of a class. In-fact, objects are variable of the type class.
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 of similar type.
Why Use a Language Like C++?
At its core, a computer is just a processor with some memory, capable of
running tiny instructions like “store 5 in memory location 23459.” Why would
we express a program as a text file in a programming language, instead of
writing processor instructions?
The advantages:
1. Conciseness: programming languages allow us to express common sequences
of commands more concisely. C++ provides some especially powerful
shorthands.
2. Maintainability: modifying code is easier when it entails just a few text edits,
instead of rearranging hundreds of processor instructions. C++ is object oriented
which further improves maintainability.
3. Portability: different processors make different instructions available.
Programs written as text can be translated into instructions for many different
processors; one of C++’s strengths is that it can be used to write programs for
nearly any processor. C++ is a high-level language: when you write a program
in it. C++ does give access to some lower-level functionality than other
languages (e.g. memory addresses)

The Compilation Process


A program goes from text files (or source files) to processor instructions as
follows:

Source File Object File Compiler Source File Object File Compiler Executable
Linker Libraries Program in Memory OS Object files are intermediate files that
represent an incomplete copy of the program: each source file only expresses a
piece of the program, so when it is compiled into an object file, the object file
has some markers indicating which missing pieces it depends on.
The linker takes those object files and the compiled libraries of predefined code
that they rely on, fills in all the gaps, and spits out the final program, which can
then be run by the operating system (OS).
The compiler and linker are just regular programs. The step in the compilation
process in which the compiler reads the file is called parsing. In C++, all these
steps are performed ahead of time, before you start running a program. In some
languages, they are done during the execution process, which takes time. This is
one of the reasons C++ code runs far faster than code in many more recent
languages. C++ actually adds an extra step to the compilation process: the code
is run through a preprocessor, which applies some modifications to the source
code, before being fed to the compiler. Thus, the modified diagram is:

Basic Program :-
// A Hello World program
# include < iostream >
int main ()
{
std :: cout << " Hello , world !\ n ";
return 0;
}

Explanation :-
1. // indicates that everything following it until the end of the line is a comment:
it is ignored by the compiler. Another way to write a comment is to put it
between /* and */ (e.g. x = 1 + /*sneaky comment here*/ 1;). A comment of this
form may span multiple lines. Comments exist to explain non-obvious things
going on in the code. Use them: document your code well!
2. Lines beginning with # are preprocessor commands, which usually change
what code is actually being compiled. #include tells the preprocessor to dump in
the contents of another file, here the iostream file, which defines the procedures
for input/output.
3. int main() {...} defines the code that should execute when the program starts
up. The curly braces represent grouping of multiple commands into a block.
More about this syntax in the next few lectures.
4. • cout << : This is the syntax for outputting some piece of text to the screen.
• Namespaces: In C++, identifiers can be defined within a context – sort of a
directory of names – called a namespace. When we want to access an identifier
defined in a namespace, we tell the compiler to look for it in that namespace
using the scope resolution operator (::).
Here, we’re telling the compiler to look for cout in the std namespace, in which
many standard C++ identifiers are defined. A cleaner alternative is to add the
following line below line 2:
using namespace std ;
This line tells the compiler that it should look in the std namespace for any
identifier we haven’t defined. If we do this, we can omit the std:: prefix when
writing cout.
• Strings: A sequence of characters such as Hello, world is known as a string. A
string that is specified explicitly in a program is a string literal.
• Escape sequences: The \n indicates a newline character. It is an example of an
escape sequence – a symbol used to represent a special character in a text literal.
Escape Sequence Represented Character
\a System bell (Beep Sound)
\b Backspace
\f Formeed (page Break)
\n Newline (line Break)
\r “Carriage return” (returns cursor to
start of line)
\t Tab
\\ Backslash
\’ Single quote character
\” Double quote character
\some integer x The character represented by x

5. return 0 indicates that the program should tell the operating system it has
completed successfully. This syntax will be explained in the context of
functions; for now, just include it as the last line in the main block.

Tokens
Tokens are the minimals chunk of program that have meaning to the compiler –
the smallest meaningful symbols in the language. Our code displays all 6 kinds
of tokens, though the usual use of operators is not present here:
Token Type Description/Purpose Examples
Keywords Words with special Int, double, for, auto
meaning to the compiler
Identifiers Names of things that are Cout, std, x, myfunction
not built into the
language
Literals Basic constant values “Hello, world!”, 24.3, 0,
whose value is specified ‘c’
directly in the source
code
Operators Mathematical or logical +, -, &&, %, <<
operation
Punctuations/Seperators Punctuation defining the {} () , ;
structure of a program
Whitespace Spaces of various sorts; Spaces, Tabs, newlines,
ignored by the compiler comments

Values and Statements


First, a few definitions:
• A statement is a unit of code that does something – a basic building block of a
program.
• An expression is a statement that has a value – for instance, a number, a string,
the sum of two numbers, etc. 4 + 2, x - 1, and "Hello, world!\n" are all
expressions.
Not every statement is an expression. It makes no sense to talk about the value
of an #include statement, for instance.
Operators
We can perform arithmetic calculations with operators. Operators act on
expressions to form a new expression. For example, we could replace "Hello,
world!\n" with (4 + 2) / 3, which would cause the program to print the number
2. In this case, the + operator acts on the expressions 4 and 2 (its operands).
Operator types:
• Mathematical: +, -, *, /, and parentheses have their usual mathematical
meanings, including using - for negation. % (the modulus operator) takes the
remainder of two numbers: 6 % 5 evaluates to 1.
• Logical: used for “and,” “or,” and so on. More on those in the next lecture.
• Bitwise: used to manipulate the binary representations of numbers. We will not
focus on these.
Data Types
Every expression has a type – a formal description of what kind of data its
value is. For instance, 0 is an integer, 3.142 is a floating-point (decimal)
number, and "Hello, world!\n" 5 is a string value (a sequence of characters).
Data of different types take a different amounts of memory to store. Here are the
built-in datatypes we will use most often:
Type Names Description Size Range
Char Single text 1 byte Signed: -128 to
character or small 127
integer: indicated Unsigned: 0 to
with single quotes 255
(‘a’ , ‘3’ )
int Larger integer 4 bytes Signed: -
2147483648 to
2147483647

Unsigned : 0 to
4294967295
Bool Boolean ( 1 bytes Just true (1) or
true/false). false (0)
Indicated with the
keywords true
and false
Double “doubly” precise 8 bytes +/-1.7e+/-308(15
floating point digit)
number.

• A signed integer is one that can represent a negative number; an unsigned


integer will never be interpreted as negative, so it can represent a wider range of
positive numbers. Most compilers assume signed if unspecified.
• There are actually 3 integer types: short, int, and long, in non-decreasing order
of size (int is usually a synonym for one of the other two). You generally don’t
need to worry about which kind to use unless you’re worried about memory
usage or you’re using really huge numbers. The same goes for the 3 floating
point types, float, double, and long double, which are in non-decreasing order of
precision (there is usually some imprecision in representing real numbers on a
computer).
• The sizes/ranges for each type are not fully standardized; those shown above
are the ones used on most 32-bit computers. An operation can only be
performed on compatible types. You can add 34 and 3, but you can’t take the
remainder of an integer and a floating-point number. An operator also normally
produces a value of the same type as its operands; thus, 1 / 4 evaluates to 0
because with two integer operands, / truncates the result to an integer. To get
0.25, you’d need to write something like 1 / 4.0.

Debugging
There are two kinds of errors you’ll run into when writing C++ programs:
compilation errors and runtime errors. Compilation errors are problems raised
by the compiler, generally resulting from violations of the syntax rules or
misuse of types. These are often caused by typos and the like. Runtime errors
are problems that you only spot when you run the program: you did specify a
legal program, but it doesn’t do what you wanted it to. These are usually more
tricky to catch, since the compiler won’t tell you about them.

Benefits of OOP
OOP offers several benefits to both the program designer and the user. Object
Orientation contributes to the solution of many problems associated with the
development and quality of software products. The new technology promises
greater programmer productivity, better quality of software and lesser
maintenance cost. The principal advantages are:
 Through inheritance, we can eliminate redundant code and extend the use
of existing classes.
 We can build programs from the standard working modules that
communicate with one another, rather than having to start writing the
code from scratch. This leads to saving of development time and higher
productivity.
 The principle of data hiding helps the programmer to build secure
programs that can not be invaded by code in other parts of the program.
 It is possible to have multiple instances of an object to co-exist without
any interference.
 It is possible to have multiple instances of an object to co-exist without
any interference.
 Software complexity can be easily managed.
 Object oriented techniques can be easily upgraded from small to large
systems.

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy