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

Unit 1-2

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)
29 views

Unit 1-2

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/ 30

oops UNIT -1 2022

Q.NO. 1(a) } When do we need to use default arguments in a function ? What is the main
advantage of passing arguments by reference ?

### Default Arguments in a Function:


Default arguments in a function are used to provide a default value for a function parameter, in case the caller
of the function does not provide a corresponding argument. They are particularly useful in the following
scenarios:

**When to Use Default Arguments:**


1. **Variety of Use Cases:** Default arguments are handy when a function can be called with different sets
of parameters, and you want to provide a default behavior for some of them.
2. **Avoid Overloading:** Instead of defining multiple overloaded functions, you can use default
arguments to handle different cases within a single function.
3. **Backward Compatibility:** When modifying existing code, introducing default arguments allows
you to maintain backward compatibility with older function calls that may not include the new parameters.

**Example:**
#include <iostream>
using namespace std;
// Function with default argument
void printMessage( string message = "Hello, World!") {
cout << message << endl;
}

int main() {
printMessage(); // Uses default argument
printMessage("Welcome!"); // Overrides default argument
return 0;
}

### Passing Arguments by Reference:


Passing arguments by reference involves providing the memory address of a variable instead of the actual
value.

**Advantages of Passing Arguments by Reference:**


1. **Efficiency:** Avoiding the copying of large data structures can significantly improve the efficiency of
your program.
2. **Memory Usage:** Reduces memory consumption as there's no need to duplicate the entire data structure.
3. **Avoids Object Slicing:** When passing derived class objects by reference to a base class parameter, it
avoids the "slicing" problem, preserving the derived class information.
4. **Modifiability:** Allows functions to modify the original values of the variables passed, making it useful
for functions that need to update multiple values.

**Example:**
#include <iostream>
using namespace std;
// Function that modifies its argument by reference
void incrementValue(int& x) {
x++;
}

int main() {
int num = 5;
cout << "Before: " << num << endl;

// Pass by reference
incrementValue(num);

cout << "After: " << num << endl;

return 0;
}

Q.NO. 1(b) } write a C++ program to swap two numbers using pointers.
// Here is C++ program swap two numbers using pointers.
#include <iostream>
using namespace std;

void swap(int* num1, int* num2) {


int temp = *num1;
*num1 = *num2;
*num2 = temp;
}

int main() {
int num1 = 5, num2 = 10;
cout << "Before swapping: " << endl;
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
swap(&num1, &num2);
cout << "After swapping: " << endl;
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
return 0;
}

Q.NO. 2(a) } Write an Object oriented program in C++ to count the number of
occurrences of the specific character in the text.

// C++ program that uses object-oriented programming to count the number of occurrences of a specific
character in a text:
#include <iostream>
#include <string>
using namespace std;
class TextAnalyzer {
private:
string text;
public:
TextAnalyzer(string t) {
text = t;
}
int countOccurrences(char c) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
if (text[i] == c) {
count++;
}
}
return count;
}
};

int main() {
string inputText;
char inputChar;
cout << "Enter a text: ";
getline(cin, inputText);
cout << "Enter a character to count: ";
cin >> inputChar;
TextAnalyzer analyzer(inputText);
int count = analyzer.countOccurrences(inputChar);
cout << "The character '" << inputChar << "' occurs " << count << " times in the text." << endl;
return 0;
}
Sample output:
Enter a text: Hello, world!
Enter a character to count: l
The character 'l' occurs 3 times in the text.

Q.NO. 2(a) } Write an object oriented program in C++ to count the number of occurrence
of the specific character in the text.

// An object oriented program in C++ to count the number of occurrence of the specific character in
the text.
#include <iostream>
#include <string>
using namespace std;
class CharacterCounter {
private:
string text;
char targetCharacter;
public:
// Constructor
CharacterCounter(const string& inputText, char targetChar) : text(inputText), targetCharacter(targetChar) {}

// Function to count occurrences of the target character


int countOccurrences() const {
int count = 0;
for (char ch : text) {
if (ch == targetCharacter) {
count++;
}
}
return count;
}
};
int main() {
// Get input text and target character from the user
string inputText;
char targetChar;
cout << "Enter a text: ";
getline(cin, inputText);
cout << "Enter the character to count: ";
cin >> targetChar;

// Create an instance of CharacterCounter


CharacterCounter counter(inputText, targetChar);

// Count occurrences and display the result


int occurrences = counter.countOccurrences();
cout << "Number of occurrences of '" << targetChar << "': " << occurrences << endl;
return 0;
}
OUTPUT
Enter a text: programming is fun and rewarding
Enter the character to count: r
Number of occurrences of 'r': 4

Q.NO. 2(b) } What is the difference between early binding and late binding in C++ ?
Early Binding (Compile-time Binding):
Early binding, also known as compile-time binding or static binding, refers to the process where the
association between a function call and the corresponding function definition is determined at compile time.

Late Binding (Run-time Binding):


Late binding, also known as run-time binding or dynamic binding, refers to the process where the association
between a function call and the corresponding function definition is determined at runtime.
Difference between Early binding and late binding
Feature Early Binding (Compile-time Binding) Late Binding (Run-time Binding)
Binding Time Occurs at compile-time. Occurs at runtime.
Other Names Static Binding, Compile-time Polymorphism. Dynamic Binding, Runtime
Polymorphism.
Example in C++ cpp class Base { public: virtual void display() {} cpp class Base { public: virtual void
}; class Derived : public Base { public: void display() {} }; class Derived : public Base
display() override {} }; int main() { Derived obj; { public: void display() override {} }; int
obj.display(); // Early binding return 0; } main() { Base* ptr = new Derived; ptr-
>display(); // Late binding delete ptr;
return 0; }
Time of Resolved at compile-time. Resolved at runtime.
Resolution
Performance Generally faster as the binding is resolved Slightly slower as the binding is resolved
during compile-time. at runtime.
Flexibility Less flexible as changes to the type hierarchy More flexible as changes can be
may require recompilation. accommodated without recompilation.

Polymorphism Supports compile-time polymorphism through Supports runtime polymorphism through


function overloading and templates. virtual functions and inheritance.

Syntax Early binding allows for better syntax checking Late binding may have limited syntax
Checking at compile-time. checking at compile-time, but issues may
surface at runtime.
Example with cpp class Calculator { public: int add(int a, int cpp class Calculator { public: virtual
Overloading b) { return a + b; } double add(double a, double double add(double a, double b) { return a
b) { return a + b; } }; int main() { Calculator + b; } }; int main() { Calculator* calc =
calc; int sumInt = calc.add(2, 3); // Early binding new Calculator; double sum = calc-
double sumDouble = calc.add(2.5, 3.7); // Early >add(2.5, 3.7); // Late binding delete calc;
binding return 0; } return 0; }
Compile-Time Errors are detected at compile-time. Errors may not be detected until runtime.
Errors
Example with cpp template <typename T> T add(T a, T b) { cpp // Late binding is not applicable to
Templates return a + b; } int main() { int sumInt = add(2, templates directly. // The concept of
3); // Early binding double sumDouble = templates is inherently an early binding
add(2.5, 3.7); // Early binding return 0; } mechanism.

Example early binding


#include <iostream>
using namespace std;

class Base {
public:
void show() {
cout << "Base class" << endl;
}
};
class Derived : public Base {
public:
void show() {
cout << "Derived class" << endl;
}
};
int main() {
Base b;
Derived d;
Base *ptr = &d; // Early binding
ptr->show(); // Calls the show() function of the Base class
return 0;
}

Example late binding


#include <iostream>
using namespace std;
class Base {
public:
virtual void show() {
cout << "Base class" << endl;
}
};

class Derived : public Base {


public:
void show() {
cout << "Derived class" << endl;
}
};

int main() {
Base *ptr = new Derived(); // Late binding
ptr->show(); // Calls the show() function of the Derived class
return 0;
}

oops UNIT -1 2018

Q.no. 1(a) , 5mks} Distinguish between object and class.

Difference between object and class

There are many differences between object and class. A list of differences between object and class are given
below:
No. Object Class
1) Object is an instance of a class. Class is a blueprint or template from which
objects are created.
2) Object is a real world entity such as pen, Class is a group of similar objects.
laptop, mobile, bed, keyboard, mouse, chair
etc.
3) Object is a physical entity. Class is a logical entity.
4) Object is created through new Class is declared using class keyword e.g.
keyword mainly e.g. class Student{}
Student s1=new Student();
5) Object is created many times as per Class is declared once.
requirement.
6) Object allocates memory when it is created. Class doesn't allocated memory when it is
created.
7) There are many ways to create object in java There is only one way to define class in java using
such as new keyword, newInstance() method, class keyword.
clone() method, factory method and
deserialization.

Q.no. 1(b) , 5mks}What are preprocessor directives in C++? Explain any three.
Preprocessor directives are special commands in C++ that are processed by the preprocessor before the actual
compilation of the code. They are used to provide instructions to the preprocessor to perform certain tasks
such as including header files, defining constants, conditional compilation, and macro substitution. Some
common preprocessor directives in C++ include #include, #define, #ifdef, #ifndef, #endif, and #pragma. These
directives help in controlling the compilation process and customizing the behavior of the code.
1. #include: This directive is used to include the contents of a header file in the source code. It allows the
programmer to use the functions, classes, and other declarations from the included file in their program. For
example, #include <iostream> is commonly used to include the input/output stream library in C++ programs.
Ex.
#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!" << endl;
return 0;
}
2. #define: This directive is used to define a macro, which is a symbolic name representing a value or a
piece of code. It is often used to define constants or to create simple functions using macros. For example,
#define PI 3.14159 defines a macro PI with the value 3.14159.
Ex.
#define PI 3.14159
int main() {
double radius = 5.0;
double area = PI * radius * radius;
return 0;
}
3. #ifdef, #ifndef, #endif: These directives are used for conditional compilation, allowing certain parts of the
code to be included or excluded based on whether a certain condition is met. #ifdef checks if a macro is
defined, #ifndef checks if a macro is not defined, and #endif marks the end of the conditional block. These
directives are often used to create code that is specific to certain platforms or configurations.
Ex.
#define DEBUG

int main() {
#ifdef DEBUG
cout << "Debug mode is enabled." << endl;
#else
cout << "Debug mode is disabled." << endl;
#endif

return 0;
}

Q.no. 2(a) , 5mks} How can you create constant object in C++? What of such objects?
In C++, you can create constant objects by using the const keyword in the object declaration. A constant
object is an object whose value cannot be modified after initialization. This is useful when you want to ensure
that the object remains unchanged throughout its lifetime.
Here's an example of how you can create a constant object in C++:
class MyClass {
public:
int value;
MyClass(int v) : value(v) {}
};

int main() {
const MyClass obj(10); // Creating a constant object
// obj.value = 20; // This would result in a compilation error because obj is a constant object
return 0;
}

Q.no. 2(b) , 5mks} What is abstract class? Why do you need them?
An abstract class in C++ is a class that is designed to be used as a base for other classes. It cannot be
instantiated on its own, but instead, it serves as a blueprint for derived classes. Abstract classes often contain
one or more pure virtual functions, which are declared using the "= 0" syntax and have no implementation in
the abstract class.
Key features of an abstract class include:
1. **Pure Virtual Functions:**
An abstract class often contains pure virtual functions, which are declared using the `virtual` keyword and
set to 0.
Example:
class Shape {
public:
virtual void draw() const = 0; // Pure virtual function
};
2. **Inheritance and Polymorphism:**
- Abstract classes are often used as base classes in an inheritance hierarchy. Derived classes inherit the
common interface and may provide their own implementations for the pure virtual functions.
- Example:
class Circle : public Shape {
public:
void draw() const override {
// Implementation for drawing a circle
}
};

**Why do you need abstract classes?**

1. **Common Interface:**
- Abstract classes allow you to define a common interface for a group of related classes. This can improve
code organization and help ensure consistency among different classes.
2. **Polymorphism:**
- Abstract classes facilitate polymorphism, allowing objects of derived classes to be treated through a
common interface. This enhances flexibility and makes it easier to work with different types of objects in a
uniform manner.
3. **Forcing Derivatives to Implement:**
- Abstract classes can define pure virtual functions, forcing derived classes to provide concrete
implementations. This ensures that every derived class adheres to a certain interface.
4. **Abstraction and Encapsulation:**
- Abstract classes contribute to the principles of abstraction and encapsulation by allowing you to hide the
implementation details of specific functionality and focus on defining a high-level interface.

Q.no. 1(a) 5mks} What is ‘::’ operator? Explain two uses of it.
The `::` operator in C++ is known as the scope resolution operator. It is used to qualify the scope of a
variable, function, or class. Here are two primary uses of the `::` operator:

1. **Accessing Class Members:**


- The `::` operator is commonly used to access members (variables or functions) of a class or namespace.
Example:
#include <iostream>

class MyClass {
public:
static int staticVar;
void display() {
std::cout << "Display function of MyClass" << std::endl;
}
};

// Definition of static variable


int MyClass::staticVar = 42;
int main() {
// Accessing static variable using scope resolution operator
std::cout << "Static variable: " << MyClass::staticVar << std::endl;

// Accessing member function using scope resolution operator


MyClass obj;
obj.display();

return 0;
}
- In this example, `MyClass::staticVar` is used to access a static variable, and `obj.display()` is used to call
the `display` member function.
2. **Defining Member Functions Outside Class Declaration:**
- The `::` operator is also used to define member functions of a class outside the class declaration. This is
often done when the function implementation is lengthy or when you want to separate the declaration and
implementation.
Example:
#include <iostream>
class MyClass {
public:
void display(); // Declaration
};

// Definition of the display member function


void MyClass::display() {
std::cout << "Display function of MyClass" << std::endl;
}

int main() {
MyClass obj;
obj.display();

return 0;
}

oops UNIT -1 2019


Q.no. 1(a) , 10mks} Distinguish between the following term :
(i) Data abstraction and Data encapsulation.
(ii) Method overloading and method overriding.

Difference between Abstraction and Encapsulation

Abstraction Encapsulation
 Abstraction can be defined as a process  Encapsulation can be defined as a process within
within which we gain information. which we encapsulate the info.

 In abstraction, we hide the data which  In encapsulation, we store or hide all the information
isn't necessary or required by the user. in a single unit and we also make a way that
prohibits any random code from accessing data from
inside. It helps in protecting data.
 Implementation of abstraction can be  Implementation of encapsulation can be done by
done by abstract class or interface. using access modifiers like private, protected, and
public.
 In the abstraction method, the  In the process of encapsulation, we hide the info
implementation complexities are usually using methods such as setters and getters.
hidden with the assistance of abstract
class and interface.

 The objects which help us in the process  In encapsulation, the performing encapsulation item
of abstraction are usually encapsulated. could also be abstracted or might not be.

 Problems in abstraction are solved at the  Problems in encapsulation are solved at the
interface level. implementation level.
Example of Abstraction:
#include <iostream>
using namespace std;
class Summation {
private:
// private variables
int a, b, c;
public:

void sum(int x, int y)


{
a = x;
b = y;
c = a + b;
cout<<"Sum of the two number is : "<<c<<endl;
}
};
int main()
{
Summation s;
s.sum(5, 4);
return 0;
}

Output:

Sum of the two number is: 9

Example of Encapsulation:

#include <iostream>
using namespace std;

class EncapsulationExample {
private:
// we declare a as private to hide it from outside
int a;

public:
// set() function to set the value of a
void set(int x)
{
a = x;
}

// get() function to return the value of a


int get()
{
return a;
}
};

// main function
int main()
{
EncapsulationExample e1;

e1.set(10);

cout<<e1.get();
return 0;
}

Output:

10
The differences between Method Overloading and Method Overriding in Java are as follows:
Method Overloading Method Overriding
Method overloading is a compile-time Method overriding is a run-time polymorphism.
polymorphism.
Method overloading helps to increase the Method overriding is used to grant the specific
readability of the program. implementation of the method which is already
provided by its parent class or superclass.
It occurs within the class. It is performed in two classes with inheritance
relationships.
Method overloading may or may not require Method overriding always needs inheritance.
inheritance.
In method overloading, methods must have In method overriding, methods must have the same
the same name and different signatures. name and same signature.
In method overloading, the return type can In method overriding, the return type must be the
or can not be the same, but we just have to same or co-variant.
change the parameter.
Static binding is being used for overloaded Dynamic binding is being used for overriding
methods. methods.
Poor Performance due to compile time It gives better performance. The reason behind this is
polymorphism. that the binding of overridden methods is being done
at runtime.
Private and final methods can be overloaded. Private and final methods can’t be overridden.
The argument list should be different while
doing method overloading.

Difference between Function Overloading and Overriding


Function Overloading Function Overriding
Function Overloading provides multiple definitions Function Overriding is the redefinition of base
of the function by changing signature. class function in its derived class with same
signature.
An example of compile time polymorphism. An example of run time polymorphism.
Function signatures should be different. Function signatures should be the same.
Overloaded functions are in same scope. Overridden functions are in different scopes.
Overloading is used when the same function has to Overriding is needed when derived class function
behave differently depending upon parameters has to do some different job than the base class
passed to them. function.
A function has the ability to load multiple times. A function can be overridden only a single time.
In function overloading, we don’t need inheritance. In function overriding, we need an inheritance
concept.
Example of function overloading
#include <iostream>
int area(int x) {
return x * x;
}
int area(int x, int y) {
return x * y;
}
float area(float r) {
return 3.14 * r * r;
}
int main() {
int areaOfSquare = area(5);
int areaOfRect = area(5, 2);
float areaOfCircle = area(5.0f);
std::cout << "Area of square with side length 5 is " << areaOfSquare << std::endl;
std::cout << "Area of rectangle with length 5 and breadth 2 is " << areaOfRect << std::endl;
std::cout << "Area of circle with radius 5.0 is " << areaOfCircle << std::endl;
return 0;
}
Output:
Area of square with side length 5 is 25
Area of rectangle with length 5 and breadth 2 is 10
Area of circle with radius 5.0 is 78.5

Example of function overriding


Class a
{
public:
virtual void display(){ cout << "hello"; }
};

Class b:public a
{
public:
void display(){ cout << "bye";}
};

Q.no. 2(a) , 10mks} What is class ? What is relation between an object and class? Write
a program which shows how to define a class, how to access member functions and how
to create and access object in C++.
In object-oriented programming, a class is a blueprint or template for creating objects. It defines a data
structure along with methods or functions that operate on the data. An object, on the other hand, is an
instance of a class, created from the class blueprint. Objects represent real-world entities and encapsulate
data and behavior.

Here's a simple example in C++ to illustrate how to define a class, access member functions, and
create/access objects:

#include <iostream>

// Define a class named "Person"


class Person {
public:
// Member variables
std::string name;
int age;

// Member function to set values


void setDetails(const std::string &n, int a) {
name = n;
age = a;
}

// Member function to display details


void displayDetails() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};

int main() {
// Create an object of class Person
Person person1;

// Access member function to set values


person1.setDetails("John Doe", 25);

// Access member function to display details


person1.displayDetails();
// Create another object and set values using a different approach
Person person2;
person2.name = "Jane Smith";
person2.age = 30;

// Display details of the second person


person2.displayDetails();

return 0;
}
Q.no. 2(b) , 5mks} Explain public, private and protected access specifiers and show
their visibility when they are inherited as a public, private and protected.
Access specifiers in C++ (public, private, and protected) define the visibility and accessibility of class
members (data members and member functions) within a class and its derived classes. Let's delve into each
access specifier:

1. **Public Access Specifier:**


- Members declared as public are accessible from any part of the program.
- They can be accessed by objects of the class, as well as by derived classes and external code.
- Public members of a class act as an interface to the outside world.

Example:
class Base {
public:
int publicMember;
};

When inherited:
- If inherited publicly, the public members of the base class remain public in the derived class.
- If inherited privately or protectedly, public members become private or protected in the derived class,
respectively.

Example:
```cpp
class DerivedPublic : public Base {
// publicMember is still public
};

2. **Private Access Specifier:**


- Members declared as private are only accessible within the class itself.
- They cannot be accessed by derived classes or external code.
- Private members are hidden from the outside world.

Example:
```cpp
class Base {
private:
int privateMember;
};

When inherited:
- Regardless of how the inheritance is specified (public, private, or protected), private members of the base
class remain private in the derived class.

Example:
```cpp
class DerivedPrivate : public Base {
// privateMember is still private and cannot be accessed here
};
```

3. **Protected Access Specifier:**


- Members declared as protected are accessible within the class and its derived classes.
- They cannot be accessed by external code.
- Protected members provide a level of encapsulation, allowing derived classes to access the internals of
the base class.

Example:
```cpp
class Base {
protected:
int protectedMember;
};
```

When inherited:
- If inherited publicly, protected members become protected in the derived class.
- If inherited privately, protected members become private in the derived class.

Example:
```cpp
class DerivedProtected : public Base {
// protectedMember is accessible as protected
};

oops UNIT -1 2021

Q.NO. 1(a) } Define object and class? Differentiate between procedure oriented and object oriented
programming.
Object: An object is a real-world entity that has a state and behavior. It can be anything from a person, a car,
a book, or even a computer program. In object-oriented programming, objects are used to represent data and
the operations that can be performed on that data.
Class: A class is a blueprint for creating objects. It defines the properties and behavior of objects of a specific
type. In other words, a class is a template for creating objects with similar attributes and methods.

Procedural Programming vs Object-Oriented Programming


Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is divided In object-oriented programming, the program is


into small parts called functions. divided into small parts called objects.

Procedural programming follows a top-down Object-oriented programming follows a bottom-


approach. up approach.

There is no access specifier in procedural Object-oriented programming has access


programming. specifiers like private, public, protected, etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any proper Object-oriented programming provides data
way of hiding data so it is less secure. hiding so it is more secure.

In procedural programming, overloading is not Overloading is possible in object-oriented


possible. programming.

In procedural programming, there is no concept of In object-oriented programming, the concept of


data hiding and inheritance. data hiding and inheritance is used.

In procedural programming, the function is more In object-oriented programming, data is more


important than the data. important than function.

Procedural programming is based on the unreal Object-oriented programming is based on the real
world. world.

Procedural programming is used for designing Object-oriented programming is used for


medium-sized programs. designing large and complex programs.

Procedural programming uses the concept of Object-oriented programming uses the concept of
procedure abstraction. data abstraction.

Code reusability absent in procedural Code reusability present in object-oriented


programming, programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

Q.NO. 1(b) } Draw comparison between Overloading vs Overriding. Give a brief note on overriding
methods.
Difference between Function Overloading and Function Overriding

(NOTE : Answer badha Chadha kar likha gaya hai, aap utna hi yaad kare jitna aap capable hai ya
jitnaa aap ko jaruri hai.)
S.No. Function Overloading Function Overriding
1. The concept through which we can define The concept through which we define a
two or more functions with the same name function in parent class and the child class
and different numbers and parameters is with the same return type and parameters is
known as function overloading. known as function overriding.
2. It can take place without inheritance. It can take place only when a class inherited
from another class.
3. It happens during compile time. It happens during run time.
4. It is also known as compile time It is also known as run time polymorphism.
polymorphism.
5. The function overloading can take place Function overriding can take place in the
multiple times. derived class only at once.
6. Here, the scope of the overloaded functions Here, the scope of the overridden function
remain the same. is different.
7. No keyword is used during function When the function is defined, it is preceded
overloading. by 'virtual' keyword in main class.
8. The functions would be redefined with the The same function is redefined in derived
same name, different number or type of class using 'out' keyword
parameters
9. Destructor can't be overloaded. Destructor can be overridden.
10. It can be used to achieve early binding. Overriding is also known as late binding.

Syntax:
The following is the syntax for function overloading:
return_typefunction_name(arguments);
Example:
#include <iostream>
using namespace std;
void print(int num) {
cout<< "Printing integer: " << num << endl;
}

void print(double num) {


cout<< "Printing double: " << num << endl;
}

int main() {
print(10);
print(3.14);
return 0;
}
OUTPUT
Printing integer: 10
Printing double: 3.14

Syntax:

The following is the syntax for overriding a function:


class Base {
public:
virtual return_typefunction_name(arguments) {
// Base class implementation
}
};

class Derived : public Base {


public:
return_typefunction_name(arguments) {
// Derived class implementation
}
};
Example:
#include <iostream>

class Shape {
public:
virtual void draw() {
cout<< "Drawing a shape." << endl;
}
};

class Circle : public Shape {


public:
void draw() {
cout<< "Drawing a circle." << endl;
}
};

int main () {
Shape* shape = new Circle();
shape->draw();
delete shape;
return 0;
}
Output:
Drawing a circle.

Q.NO. 2(a) } What is a Structure? Why we need structure definition? How to access
members of structures?

**Structure:**
In programming, a structure is a composite data type that groups together variables of different data types
under a single name. It allows you to create a collection of related data items, each with its own data type,
and organize them in a way that makes it easy to manipulate and manage.

**Why We Need Structure Definition:**


1. **Organizing Data:** Structures help in organizing and representing complex data in a more logical and
meaningful way.
2. **Grouping Related Information:** When you have a set of related variables that need to be treated as
a unit, a structure allows you to group them together.
3. **Passing Data to Functions:** Structures are often used to pass a collection of related data to functions
as a single parameter.
4. **Data Modeling:** In situations where real-world entities have multiple attributes, structures can be
used to model and represent those entities.

**How to Access Members of Structures:**


To access members (variables or fields) of a structure, you use the member access operator (`.`). The general
syntax is:

Syntax
structureVariable.memberName;
```
Here's a simple example in C++:

#include <iostream>

// Define a structure representing a point in 2D space


struct Point {
int x;
int y;
};

int main() {
// Declare and initialize a structure variable
Point p1 = {3, 5};

// Access and print the values of structure members


cout << "X coordinate: " << p1.x << endl;
cout << "Y coordinate: " << p1.y << endl;

return 0;
}
Q.NO. 2(b) } Define the ‘this’ pointer with an example, indicate the steps involved in referring to
members of the invoking object.

The `this` pointer is a keyword in C++ that is used as a pointer to the object for which a member function is
invoked. It represents the address of the current object and allows you to access the members of the object
within the member function. The `this` pointer is implicitly available within the scope of every non-static
member function.

Here's an example to illustrate the use of the `this` pointer:


#include <iostream>
class MyClass {
private:
int value;

public:
// Constructor to initialize the value
MyClass(int val) : value(val) {}

// Member function to display the value using 'this' pointer


void displayValue() {
// Accessing the member 'value' using 'this' pointer
cout << "Value: " << this->value << endl;

// 'this' pointer is implicitly used, so the following is equivalent:


// cout << "Value: " << value << endl;
}

// Member function to compare the value with another value


bool isEqual(int otherValue) {
// Using 'this' pointer explicitly is optional in this case
return this->value == otherValue;
}
};

int main() {
// Creating an instance of MyClass
MyClass obj(42);

// Invoking member functions


obj.displayValue();

// Checking equality using the isEqual function


if (obj.isEqual(42)) {
cout << "The values are equal." << endl;
} else {
cout << "The values are not equal." << endl;
}

return 0;
}
Referring to members of the invoking object in C++ involves using the `this` pointer within a member
function. The `this` pointer is implicitly available in the scope of every non-static member function and
points to the object for which the function is called. Here are the steps involved in referring to members of
the invoking object:

1. **Define a Class:**
Start by defining a class with member variables and member functions.

class MyClass {
private:
int value;

public:
MyClass(int val) : value(val) {}

void displayValue() {
// Step 2: Use 'this' pointer to access members
cout << "Value: " << this->value << endl;

2. **Use the `this` Pointer:**


Within a member function, use the `this` pointer to access members of the current object.
void displayValue() {
// 'this' pointer is implicitly available
cout << "Value: " << this->value << endl;
}

3. **Optional Explicit Use of `this`:**


The use of `this` pointer is optional in most cases. You can directly access members without explicitly
using `this`.

void displayValue() {
// 'this' pointer is optional in this case
cout << "Value: " << value << endl;
}

4. **Avoiding Ambiguity:**
Use `this` pointer to avoid ambiguity when there is a local variable with the same name as a member
variable.
void setValue(int value) {
// Use 'this' pointer to refer to the member variable
this->value = value;
}

5. **Accessing Members in Other Member Functions:**


The `this` pointer can be used in multiple member functions of the same class to access members
consistently.

void displayInfo() {
// Using 'this' pointer in another member function
cout << "Info: " << this->value << endl;
}
By following these steps, you can effectively refer to members of the invoking object using the `this` pointer
within member functions of a C++ class.

OTHER REMAINING PARTS OF UNIT -1


Introductioon of C++

**Introduction to C++:**

C++ is a general-purpose programming language that was developed as an extension of the C programming
language. It was created by Bjarne Stroustrup at Bell Labs in the early 1980s. C++ is known for providing
low-level access to memory, efficient manipulation of hardware resources, and a versatile set of features that
support both procedural and object-oriented programming paradigms.

**Key Features of C++:**

1. **C Compatibility:** C++ maintains a high degree of compatibility with the C language. Many C
programs can be compiled and run as C++ programs.

2. **Object-Oriented Programming (OOP):** C++ supports the principles of object-oriented


programming, including classes, objects, encapsulation, inheritance, and polymorphism. This allows for
better organization and design of code.

3. **Efficiency:** C++ allows direct manipulation of memory, enabling efficient use of system resources. It
provides features like pointers and manual memory management for fine-grained control over memory.

4. **Standard Template Library (STL):** C++ includes a powerful and versatile library known as the
Standard Template Library (STL), which provides generic algorithms and data structures like vectors, lists,
and maps.

5. **Portability:** C++ programs can be written in a way that is highly portable across different platforms
and operating systems, making it suitable for a wide range of applications.

6. **Rich Standard Library:** In addition to the STL, C++ has a rich standard library that provides a
variety of functions for input/output operations, string manipulation, file handling, and more.

7. **Multi-Paradigm Language:** C++ supports multiple programming paradigms, including procedural


programming, object-oriented programming, and generic programming. This flexibility allows developers to
choose the most suitable approach for a given task.

8. **Operator Overloading:** C++ allows overloading of operators, enabling the creation of custom
behaviors for operators, which can simplify code and make it more expressive.

9. **Compiled Language:** C++ is a compiled language, and the source code needs to be compiled into
machine code before execution. This compilation process often results in highly efficient and optimized
code.

**Hello World Example in C++:**

Here's a simple "Hello, World!" program in C++:


#include <iostream>
using namespace std;
int main() {
// Output "Hello, World!" to the console
cout << "Hello, World!" << endl;

// Return 0 to indicate successful execution


return 0;

OUTPUT
Hello, World!

C++ standard Library


The C++ Standard Library, often referred to as the Standard Template Library (STL), is a powerful
collection of pre-built classes and functions that provides common functionality to C++ programmers. It is
an essential part of C++ programming and offers a wide range of tools for various tasks, including data
structures, algorithms, input/output operations, and more.

Key components of the C++ Standard Library include:

1. **Input/Output Streams:**
- `<iostream>`: Provides classes like `cin` (standard input) and `cout` (standard output) for basic input and
output operations.

2. **Containers:**
- `<vector>`: Implements dynamic arrays with automatic resizing.
- `<list>`: Implements doubly-linked lists.
- `<deque>`: Implements double-ended queues.
- `<queue>`: Provides queue data structure.
- `<stack>`: Provides stack data structure.
- `<set>`: Implements a sorted set of unique keys.
- `<map>`: Implements a sorted associative container of key-value pairs.

3. **Algorithms:**
- `<algorithm>`: Includes a collection of algorithms for sorting, searching, and manipulating elements in
containers.
- `<numeric>`: Provides numeric operations.
4. **Iterators:**
- `<iterator>`: Contains classes and functions for working with iterators, which enable traversal of
sequences.
5. **Strings:**
- `<string>`: Implements the ` string` class for handling strings.
6. **Input/Output File Operations:**
- `<fstream>`: Provides classes for file input and output operations.
7. **Memory Management:**
- `<memory>`: Includes utilities for dynamic memory management, smart pointers, and allocators.
8. **Concurrency:**
- `<thread>`: Provides classes and functions for multi-threading.
- `<mutex>`, `<condition_variable>`: Implements synchronization primitives.
9. **Time and Date:**
- `<chrono>`: Contains classes and functions for time-related operations.
10. **Utilities:**
- `<utility>`: Includes various utility components, such as pairs and the ` swap` function.
11. **Random Numbers:**
- `<random>`: Provides facilities for generating pseudo-random numbers.
12. **Exception Handling:**
- `<stdexcept>`: Defines standard exception classes.

The C++ Standard Library simplifies many common programming tasks and promotes code reuse. It is an
integral part of C++ development and allows programmers to focus on problem-solving rather than low-
level implementation details. Learning to effectively use the C++ Standard Library is crucial for becoming a
proficient C++ programmer.

Illustrative Simple C++ Programs

Illustrative simple C++ programs are small, concise programs that demonstrate specific concepts, features,
or tasks in the C++ programming language. These programs are designed to be easy to understand and serve
as examples for beginners or anyone learning C++. Below are a few illustrative simple C++ programs along
with explanations:

### 1. **Hello, World! Program:**

#include <iostream>
int main() {
cout << "Hello, World!" << endl;
return 0;
}
```
**Explanation:** This is the classic "Hello, World!" program, which demonstrates the basic structure
of a C++ program. It includes the `<iostream>` header for input/output operations and uses ` cout` to
print the message.

### 2. **Sum of Two Numbers:**


```cpp
#include <iostream>

int main() {
int num1, num2;

cout << "Enter two numbers: ";


cin >> num1 >> num2;
int sum = num1 + num2;
cout << "Sum: " << sum << endl;
return 0;
}
- **Explanation:** This program prompts the user to enter two numbers, calculates their sum, and then
prints the result. It demonstrates basic input/output and arithmetic operations.

### 3. **Factorial Calculation:**


#include <iostream>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

int main() {
int num;
cout << "Enter a number: ";
cin >> num;
int result = factorial(num);
cout << "Factorial: " << result << endl;
return 0;
}
```
- **Explanation:** This program calculates the factorial of a number using a recursive function. It
introduces the concept of functions and recursion.

### 4. **Simple Class and Object:**


#include <iostream>
class Circle {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double calculateArea() {
return 3.14 * radius * radius;
}
};
int main() {
Circle myCircle(5.0);
double area = myCircle.calculateArea();
cout << "Area of the circle: " << area << endl;
return 0;
}
- **Explanation:** This program defines a simple class `Circle` with a private member `radius` and a
method to calculate the area. It demonstrates the basics of object-oriented programming in C++.
### 5. **Vector and Iteration:**
#include <iostream>
#include <vector>
int main() {
vector<int> numbers = {1, 2, 3, 4, 5};
cout << "Elements of the vector: ";
for (int num : numbers) {
cout << num << " ";
}
return 0;
}
Header files
C++ offers its users a variety of functions, one of which is included in header files. In C++, all
the header files may or may not end with the “.h” extension but in C, all the header files must
necessarily end with the “.h” extension.
A header file contains:

1. Function definitions
2. Data type definitions
3. Macros
It offer above features by importing them into the program with the help of a preprocessor
directive “#include”. These preprocessor directives are used for instructing compiler that these
files need to be processed before compilation.
In C program should necessarily contain the header file which stands for standard input and output
used to take input with the help of scanf() and printf() function respectively.
In C++ program has the header file which stands for input and output stream used to take input
with the help of “cin” and “cout” respectively.
There are of 2 types of header file:

1. Pre-existing header files: Files which are already available in C/C++ compiler we just need to
import them.
2. User-defined header files: These files are defined by the user and can be imported
using “#include”.
Syntax:

#include <filename.h>
or
#include "filename.h"
// C++ program to find the sum of two
// numbers using function declared in
// header file
#include "iostream"

// Including header file


#include "sum.h"
using namespace std;

// Driver Code
int main()
{

// Given two numbers


int a = 13, b = 22;

// Function declared in header


// file to find the sum
cout << "Sum is: "
<< sumOfTwoNumbers(a, b)
<< endl;
}
 Below is the output of the above program:

Below are some inbuilt header files in C/C++:

1. #include<stdio.h>: It is used to perform input and output operations using


functions scanf() and printf().
2. #include<iostream>: It is used as a stream of Input and Output using cin and cout.
3. #include<string.h>: It is used to perform various functionalities related to string manipulation
like strlen(), strcmp(), strcpy(), size(), etc.
4. #include<math.h>: It is used to perform mathematical operations like sqrt(), log2(), pow(),
etc.
5. #include<iomanip.h>: It is used to access set() and setprecision() function to limit the decimal
places in variables.
6. #include<signal.h>: It is used to perform signal handling functions like signal() and raise().
7. #include<stdarg.h>:It is used to perform standard argument functions
like va_start() and va_arg(). It is also used to indicate start of the variable-length argument
list and to fetch the arguments from the variable-length argument list in the program
respectively.
8. #include<errno.h>: It is used to perform error handling operations
like errno(), strerror(), perror(), etc.
9. #include<fstream.h>: It is used to control the data to read from a file as an input and data to
write into the file as an output.
10. #include<time.h>: It is used to perform functions related to date() and time() like setdate()
and getdate(). It is also used to modify the system date and get the CPU time respectively.

Namespace
 amespace provide the space where we can define or declare identifier i.e. variable, method,
classes.
 Using namespace, you can define the space or context in which identifiers are defined i.e.
variable, method, classes. In essence, a namespace defines a scope.

Defining a Namespace:

 A namespace definition begins with the keyword namespace followed by the namespace name
as follows:
namespace namespace_name
{
// code declarations i.e. variable (int a;)
method (void add();)
classes ( class student{};)
}

Advantage of Namespace to avoid name collision.

 Example, you might be writing some code that has a function called xyz() and there is another
library available which is also having same function xyz(). Now the compiler has no way of
knowing which version of xyz() function you are referring to within your code.
 A namespace is designed to overcome this difficulty and is used as additional information to
differentiate similar functions, classes, variables etc. with the same name available in different
libraries.
 The best example of namespace scope is the C++ standard library (std) where all the classes,
methods and templates are declared. Hence while writing a C++ program we usually include
the directive using namespace std;

#include <iostream>
using namespace std;
// first name space
namespace first_space
{
void func()
{
cout << "Inside first_space" << endl;
}
}

// second name space


namespace second_space
{
void func()
{
cout << "Inside second_space" << endl;
}
}
using namespace first_space;
int main ()
{
// This calls function from first name space.
func();
return 0;
}

Output
Inside first_space

Application of Object Oriented Programming

Object-Oriented Programming (OOP) is a programming paradigm that is widely used due to its ability to
simplify the software development process and make the code more maintainable, flexible, and secure. Here
are some of the key applications of OOP:
1. Real-Time Systems: OOP techniques make it easier to handle the complexities of real-time
systems12.
2. Hypertext and Hypermedia: OOP helps in laying the framework for hypertext and hypermedia12.
3. AI and Expert Systems: These are computer applications developed to solve complex problems.
OOP helps to develop such systems2.
4. Office Automation Systems: These include electronic systems primarily concerned with
information sharing and communication. OOP helps in making office automation systems2.
5. Neural Networks and Parallel Programming: OOP simplifies the approximation and prediction
ability of the network1.
6. Simulation and Modeling Systems: OOP provides an appropriate approach for simplifying
complex models2.
7. Object-Oriented Databases: The databases try to maintain a direct correspondence between the real
world and database objects2.
8. Client-Server Systems: Object-oriented client-server systems provide the IT infrastructure for
creating applications2.
9. CIM/CAD/CAM Systems: OOP can be used in manufacturing and designing applications as it
allows people to reduce the efforts involved2.
10. User Interface Design: Such as windows, menus3.

You might also like