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

Unit 1 C C Notes

Uploaded by

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

Unit 1 C C Notes

Uploaded by

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

lOMoARcPSD|32556052

Unit 1 c++ - c++ notes

c+ language (Guru Gobind Singh Indraprastha University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Athul Raj ([email protected])
lOMoARcPSD|32556052

Object Oriented Programming with C++


(BCA-205)
Q1) Differences between Procedural and Object Oriented Programming.
Procedural Programming
Procedural Programming can be defined as a programming model which is derived from structured
programming, based upon the concept of calling procedure.

Object-Oriented Programming
Object-oriented programming can be defined as a programming model which is based upon the
concept of objects. Objects contain data in the form of attributes and code in the form of methods.

Procedural Programming vs Object-Oriented Programming


Below are some of the differences between procedural and object-oriented programming:

Procedural Oriented Programming Object-Oriented Programming


• In procedural programming, the program • In object-oriented programming, the
is divided into small parts called program is divided into small parts called
functions. objects.
• Procedural programming follows a top- • Object-oriented programming follows a
down approach. bottom-up approach.
• Object-oriented programming has access
• There is no access specifier in
specifiers like private, public, protected,
procedural programming.
etc.
• Adding new data and functions is not
• Adding new data and function is easy.
easy.
• Procedural programming does not have
• Object-oriented programming provides
any proper way of hiding data so it is
data hiding so it is more secure.
less secure.
• In procedural programming, overloading • Overloading is possible in object-
is not possible. oriented programming.
• In object-oriented programming, the
• In procedural programming, there is no
concept of data hiding and inheritance is
concept of data hiding and inheritance.
used.
• In procedural programming, the function • In object-oriented programming, data is
is more important than the data. more important than function.
• Procedural programming is based on the • Object-oriented programming is based on
unreal world. the real world.
• Procedural programming is used for 4 • Object-oriented programming is used for
designing medium-sized programs. designing large and complex programs.
• Code reusability absent in procedural • Code reusability present in object-
programming, oriented programming.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

Q2. Object-oriented programming – As the name suggests uses objects in programming. Object-
oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that
function.

There are some basic concepts that act as the building blocks of OOPs i.e.
1. Class
2. Objects
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance
7. Dynamic Binding
8. Message Passing

Characteristics of an Object-Oriented Programming Language

Q3) Difference between C and C++


Similarities between C and C++ are:
• Both the languages have a similar syntax.
• Code structure of both the languages are same.
• The compilation of both the languages is similar.
• They share the same basic syntax. Nearly all of C’s operators and keywords are also present
in C++ and do the same thing.
• C++ has a slightly extended grammar than C, but the basic grammar is the same.
• Basic memory model of both is very close to the hardware.
• Same notions of stack, heap, file-scope and static variables are present in both the languages.

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

C C++
• C was developed by Dennis Ritchie
• C++ was developed by Bjarne Stroustrup
between the year 1969 and 1973 at
in 1979.
AT&T Bell Labs.
• C does no support polymorphism,
• C++ supports polymorphism,
encapsulation, and inheritance which
encapsulation, and inheritance because it is
means that C does not support object
an object oriented programming language.
oriented programming.
• C is (mostly) a subset of C++. • C++ is (mostly) a superset of C.
• C++ is known as hybrid language because
• For the development of code, C
C++ supports both procedural and object
supports procedural programming.
oriented programming paradigms.
• Data and functions are separated in C
• Data and functions are encapsulated
because it is a procedural programming
together in form of an object in C++.
language.
• Data is hidden by the Encapsulation to
• C does not support information hiding. ensure that data structures and operators
are used as intended.
• Built-in & user-defined data types is
• Built-in data types is supported in C.
supported in C++.
• C is a function driven language because
• C++ is an object driven language because
C is a procedural programming
it is an object oriented programming.
language.
• Function and operator overloading is • Function and operator overloading is
not supported in C. supported by C++.
• C is a function-driven language. • C++ is an object-driven language
• Functions in C are not defined inside • Functions can be used inside a structure in
structures. C++.
• Namespace features are not present • Namespace is used by C++, which avoid
inside the C. name collisions.
• Standard IO header is stdio.h. • Standard IO header is iostream.h.
• Reference variables are not supported
• Reference variables are supported by C++.
by C.
• Virtual and friend functions are not • Virtual and friend functions are supported
supported by C. by C++.
• C does not support inheritance. • C++ supports inheritance.
• Instead of focusing on data, C focuses • C++ focuses on data instead of focusing
on method or process. on method or procedure.
• C provides malloc() and calloc()
• C++ provides new operator for memory
functions for dynamic memory
allocation and delete operator for memory
allocation, and free() for memory de-
de-allocation.
allocation.
• Direct support for exception handling
• Exception handling is supported by C++.
is not supported by C.

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

• scanf() and printf() functions are used • cin and cout are used for input/output in
for input/output in C. C++.
• C structures don’t have access
• C ++ structures have access modifiers.
modifiers.
• C follows the top-down approach • C++ follows the Bottom-up approach
• Strict type checking in done in C++. So
• There is no strict type checking in C many programs that run well in C
programming language. compiler will result in many warnings and
errors under C++ compiler.
• C does not support overloading • C++ does support overloading
• Type punning with unions is undefined
• Type punning with unions is allows
behavior (except in very specific
(C99 and later)
circumstances)
• Named initializers may appear out of • Named initializers must match the data
order layout of the struct
• File extension is “.cpp” or “.c++” or “.cc”
• File extension is “.c”
or “.cxx”
• Meta-programming: macros + • Meta-programming: templates (macros are
_Generic() still supported but discouraged)
• There are 32 keywords in the C • There are 97 keywords in the C++

Q4) Stream-based I/O:


In C++, stream-based I/O is commonly performed using the iostream library. The primary
stream objects are cin (for input) and cout (for output).

cpp

#include <iostream>
using namespace std;

int main() {
int number;

// Input
cout << "Enter a number: ";
cin >> number;

// Output
cout << "You entered: " << number << endl;

return 0;
}

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

Q5)Literals and Constant Qualifiers:

Literals are representations of specific values in a program. Constant qualifiers (const) are used
to create constants.

The const qualifier is used to create constants, making variables read-only after
initialization.

#include<iostream.h>
using namespace std;

// it does not change


const int constantValue = 10;

int main() {
int variable = 5;
variable = constantValue; // Error, cannot modify a constant

return 0;
}

Q6) C++ Operators

Operators are used to perform operations on variables and values.


C++ divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Arithmetic operators

Operator Name Description Example


+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
Increases the value of a variable by
++ Increment ++x
1
Decreases the value of a variable
-- Decrement --x
by 1
Assignment operators

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

Assignment operators are used to assign values to variables.

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.

Operator Name Example


== Equal to x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical Operators
As with comparison operators, you can also test for true (1) or false (0) values with logical
operators.
Logical operators are used to determine the logic between variables or values:

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

Operator Name Description Example


&& Logical and Returns true if both statements are true x < 5 && x < 10
|| Logical or Returns true if one of the statements is true x < 5 || x < 4
Reverse the result, returns false if the result is
! Logical not !(x < 5 && x < 10)
true

Q7). Reference Variables:


A reference variable in C++ provides an alternative name (alias) for an existing variable. It is
essentially a way to access the same memory location using a different name. Reference variables
are declared using the & symbol. Here are some important aspects of reference variables:

Basic Declaration and Initialization:

int original = 42;


int &ref = original; // 'ref' is a reference to 'original'

Now, both original and ref refer to the same memory location. Any changes made through one
variable will affect the other.

Q8) C++ Functions:

• A function is a block of code which only runs when it is called.


• You can pass data, known as parameters, into a function.
• Functions are used to perform certain actions, and they are important for reusing code:
Define the code once, and use it many times.

Example:

// Function declaration
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction() {
cout << "I just got executed!";
}

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

Example:

void display(int x, int y = 0) {


cout << "Values: " << x << ", " << y << endl;
}

int main() {
display(5); // Outputs: Values: 5, 0

return 0;
}

Q9. Parameter Passing (by Value, Reference, and Pointer):


Passing by Value:
In C++, when you pass a parameter by value, a copy of the actual parameter is created and passed to
the function. Changes made to the parameter inside the function do not affect the original variable.

void modifyValue(int x) {
x = x * 2;
}

int main() {
int number = 5;
modifyValue(number);
// 'number' remains 5, as it was passed by value
return 0;
}

Passing by Reference:
When you pass a parameter by reference, you are providing the function with direct access to the
memory location of the actual parameter. Any modifications made to the parameter inside the
function will affect the original variable.

void modifyValue(int &x) {


x = x * 2;
}

int main() {
int number = 5;
modifyValue(number);
// 'number' is now 10, as it was passed by reference
return 0;
}

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

Passing by Pointer:
Passing by pointer involves passing the memory address of the actual parameter. Like passing by
reference, changes made through the pointer inside the function affect the original variable.
cpp

void modifyValue(int *x) {


*x = *x * 2;
}

int main() {
int number = 5;
modifyValue(&number);
// 'number' is now 10, as it was passed by pointer
return 0;
}

Choosing Between Them:


• Pass by Value:
• Use when the function does not need to modify the original value.
• Suitable for small-sized data types.
• Pass by Reference:
• Use when the function needs to modify the original value.
• Avoids the overhead of copying for larger data types.
• Pass by Pointer:
• Similar to passing by reference, but allows for operations like pointer arithmetic.
• Useful for dynamic memory allocation scenarios.

Q10. Inline Functions:


In C++, an inline function is a function that the compiler is encouraged to expand in place at the
point of each function call, rather than generating a function call. This is achieved by using the
inline keyword.

Basic Syntax:
cpp

inline int add(int a, int b) {


return a + b;
}

Here, the inline keyword suggests to the compiler that it should attempt to insert the function
code directly at the call site rather than generating a function call.

Advantages of Inline Functions:


1. Reduced Function Call Overhead:

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

• Since the function code is inserted directly at the call site, there is no overhead
associated with function calls.
2. Performance Improvement:
• Inline functions can lead to performance improvements, especially for small,
frequently called functions.
3. Avoiding Function Call Stack Overhead:
• Inline functions avoid the stack overhead associated with function calls, making
them efficient for certain scenarios.

Guidelines for Using Inline Functions:


1. Use for Small Functions:
• Inline functions are most effective for small, frequently used functions. They may not
provide significant benefits for larger functions.
2. Avoid for Recursive Functions:
• Inline functions are not suitable for recursive functions.
3. Definition in Header Files:
• Typically, inline functions are defined in header files to ensure that the function
definition is available at the point of call in multiple translation units.
4. Compiler Discretion:
• The inline keyword is a suggestion to the compiler. The compiler may choose to
ignore the request based on optimization settings or other factors.

Example:

#include <iostream>

// Inline function definition in header file


inline int square(int x) {
return x * x;
}

int main() {
int number = 5;
cout << "Square of " << number << " is: " << square(number) << endl;

return 0;
}

Q11) Type Conversion:


Type conversion, also known as casting, is the process of converting one data type to another in C+
+. There are two main types of type conversion: implicit and explicit.

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

Implicit Type Conversion (Coercion):


Implicit type conversion, also known as coercion, is performed by the compiler automatically when
it is safe and does not result in loss of information. For example:

int integerNumber = 42;


double doubleNumber = integerNumber; // Implicit conversion from int to double

In this case, the int value is implicitly converted to a double without the need for explicit
casting.

Explicit Type Conversion (Casting):


Explicit type conversion requires the programmer to specify the conversion explicitly. There are
several ways to perform explicit type conversion in C++:
1. C-style Casting:
• This is an older style of casting and is generally not recommended due to its lack of
safety checks.

double doubleNumber = (double)integerNumber; // C-style casting

• Functional Casting:
• C++ introduces functional casting operators, such as static_cast, dynamic_cast,
const_cast, and reinterpret_cast.
cpp

• double doubleNumber = static_cast<double>(integerNumber); // static_cast

• static_cast is safer than C-style casting and is used for most type conversions.

• Type Conversion Functions:


• Some classes define conversion functions to convert objects of one type to another.
cpp

3. class MyClass {
public:
operator double() const {
// Define how MyClass is converted to double
return 42.0;
}
};

MyClass myObject;
double convertedValue = static_cast<double>(myObject);

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

Type Promotion and Demotion:


• Type Promotion:
• Automatic conversion of a lower-ranking data type to a higher-ranking data type to
avoid loss of precision.
• Example: int to double.
• Type Demotion:
• Explicit conversion of a higher-ranking data type to a lower-ranking data type.
• Example: double to int. This may result in loss of information.

Example:
cpp

#include <iostream>

int main() {
int integerNumber = 42;
double doubleNumber = static_cast<double>(integerNumber); // Explicit
conversion

cout << "Integer: " << integerNumber << endl;


cout << "Double: " << doubleNumber << endl;

return 0;
}

derstanding type conversion is important for writing robust and efficient code, especially when
dealing with different data types in C++. It helps prevent unexpected behavior and ensures that data
is used appropriately in various contexts.

Q12. new and delete Operators - Dynamic Memory Allocation


for Arrays:
Dynamic Memory Allocation:
In C++, dynamic memory allocation allows you to allocate memory at runtime rather than compile
time. This is particularly useful when the size of the data structure is not known until the program is
running. The new and delete operators are used for dynamic memory allocation and
deallocation.

new Operator:
The new operator is used to allocate memory for a single object or an array. When allocating
memory for an array, the size is specified in square brackets.
cpp

int* singleValue = new int; // Allocate memory for a single integer


int* arrayValues = new int[5]; // Allocate memory for an array of five integers

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

delete Operator:
The delete operator is used to deallocate memory that was previously allocated using new. When
deleting an array, use square brackets to indicate that it's an array.
cpp

delete singleValue; // Deallocate memory for a single integer


delete[] arrayValues; // Deallocate memory for an array of integers

It's crucial to use delete (or delete[] for arrays) to free up the memory to prevent memory
leaks.

Dynamic Memory Allocation for Arrays:


cpp

#include <iostream>

int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;

// Dynamic memory allocation for an array


int* dynamicArray = new int[size];

// Initialize the array


for (int i = 0; i < size; ++i) {
dynamicArray[i] = i * 10;
}

// Access and display array elements


for (int i = 0; i < size; ++i) {
cout << dynamicArray[i] << " ";
}

// Deallocate the dynamically allocated memory


delete[] dynamicArray;

return 0;
}

This program dynamically allocates an array based on user input, initializes the array, and then
deallocates the memory when it's no longer needed.

vector as an Alternative:
In modern C++, using vector is often preferred over dynamic arrays because it provides
dynamic array functionality with additional safety features, automatic memory management, and is
part of the C++ Standard Library.
cpp

#include <iostream>
#include <vector>

int main() {
int size;
cout << "Enter the size of the vector: ";

Downloaded by Athul Raj ([email protected])


lOMoARcPSD|32556052

cin >> size;

// Dynamic array functionality using vector


vector<int> dynamicVector(size);

// Initialize the vector


for (int i = 0; i < size; ++i) {
dynamicVector[i] = i * 10;
}

// Access and display vector elements


for (int value : dynamicVector) {
cout << value << " ";
}

// No need to deallocate memory, as it is managed by vector

return 0;
}

Using vector simplifies memory management and provides safety against common pitfalls
associated with raw dynamic arrays.

Downloaded by Athul Raj ([email protected])

You might also like