0% found this document useful (0 votes)
13 views11 pages

1) What Is Encapsulation?

The document provides an overview of key concepts in C++ programming, including encapsulation, binding types, inline functions, streams, friend functions, dynamic memory allocation, virtual functions, user-defined data types, constructors, function overloading, inheritance types, and exception handling. It also includes code examples demonstrating file manipulation, operator overloading, and static member functions. Additionally, it explains the use of manipulators and provides sample programs to illustrate these concepts.

Uploaded by

rohitjadhav
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)
13 views11 pages

1) What Is Encapsulation?

The document provides an overview of key concepts in C++ programming, including encapsulation, binding types, inline functions, streams, friend functions, dynamic memory allocation, virtual functions, user-defined data types, constructors, function overloading, inheritance types, and exception handling. It also includes code examples demonstrating file manipulation, operator overloading, and static member functions. Additionally, it explains the use of manipulators and provides sample programs to illustrate these concepts.

Uploaded by

rohitjadhav
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/ 11

1)What is Encapsulation?

ans:-Encapsulation is one of the fundamental principles of object-oriented programming


(OOP). It refers to the bundling of data and methods (functions) that operate on that data
into a single unit or class. This unit restricts access to some of its components, typically
hiding the internal state of an object and only allowing access through well-defined
interfaces.b) Define the following terms

1) Early Binding
ii) Late Binding
Early Binding:
Early binding, also known as static binding or compile-time binding, refers to the process of
linking a function call with the corresponding function definition at compile time. This means
that the address of the function to be executed is determined at compile time based on the
static type of the object or variablei)
Late Binding:
Late binding, also known as dynamic binding or runtime binding, refers to the process of
determining the function to be called at runtime, based on the dynamic (runtime) type of the
object or pointer. This allows for polymorphic behavior, where a function call is resolved
according to the actual type of the object being referred to.

c) What is Inline function?


ans:-An inline function is a function that the compiler treats differently from a regular function
during the compilation process. When a function is declared as inline, the compiler inserts
the entire body of the function at each point in the code where the function is called, instead
of generating a separate function call.

d) Explain get() and put () function.


ans:-get() function:
The get() function is used to read characters from the input stream (cin).
It reads characters from the input stream until a specified delimiter or the end-of-file (EOF) is
encountered. put() function:
The put() function is used to write characters to the output stream (cout).
It writes a single character to the output stream.

e) What is stream?
a stream is a sequence of data elements made available over time. These data elements
can be characters, bytes, or any other basic data type. Streams are commonly used for input
and output operations, allowing data to be read from or written to various sources, such as
files, network connections, or even memory.
1.Input stream 2 output stream

f) Define Friend function.


ans:--friend function is a function that is granted special access to the private and protected
members of a class. It is declared within a class, but it is not a member of that class. Instead,
it is a standalone function that can access the private and protected members of the class as
if it were a member function.friend function is a function that is granted special access to the
private and protected members of a class. It is declared within a class, but it is not a member
of that class. Instead, it is a standalone function that can access the private and protected
members of the class as if it were a member function.

g) Explain the use of new opreator, state the syntax.


ans:-new operator is used to dynamically allocate memory for objects or arrays during
runtime from the free store (also known as the heap). It is often used when the size of
memory needed is not known at compile time or when the lifetime of the allocated memory
needs to extend beyond the scope of the current function.
syntax:-pointer_variable = new data_type;

h) State the need of virtual keyword.?


ans:-
The virtual keyword in C++ is primarily used in the context of inheritance and polymorphism.
Its main purpose is to enable runtime polymorphism, which allows a derived class pointer or
reference to invoke the appropriate overridden function based on the actual type of the
object being referred to.

i) State user defined data types in C++.


ans:- user-defined data types are data types that are defined by the programmer rather than
being built into the language.
Classes:
Structures:
Enumerations (Enums):
Typedefs:

j) Explain the use of Scope Resolution operator.


ans:-In C++, the scope resolution operator (::) is used to access variables, functions, and
classes that are defined in a particular scope. It allows you to specify the scope or
namespace from which you want to access a particular identifier.

1)List different types of constructor. Explain any one constructor with example.
ans:-n object-oriented programming, a constructor is a special type of method that is used to
initialize objects. Constructors are called when an object is created, and they are responsible
for setting the initial values of the object's fields.
There are many different types of constructors, but some of the most common include:
Default constructors:
Parameterized constructors
Copy constructors:.
Static constructors:.
Copy Constructor:
A copy constructor is a constructor that initializes an object by copying the data of another
object of the same class. It is invoked when an object is passed by value or returned by
value.
cpp
Copy code
class MyClass {
public:
MyClass(const MyClass& other) {
// Copy constructor
}
};b) What is function overloading? Explain with suitable example.
ans:-Function overloading is a feature in C++ that allows multiple functions in the same
scope to have the same name but with different parameter lists. This enables you to define
several functions with the same name but with different functionalities based on the types
and/or number of parameters they accept.
#include <iostream>

// Function to calculate the area of a rectangle


int area(int length, int width) {
return length * width;
}

// Function to calculate the area of a circle


double area(double radius) {
return 3.14 * radius * radius;
}

// Function to calculate the volume of a cylinder


double area(double radius, int height) {
return 3.14 * radius * radius * height;
}

int main() {
// Calculate area of a rectangle
int rectangleArea = area(4, 5);
std::cout << "Area of rectangle: " << rectangleArea << std::endl;

// Calculate area of a circle


double circleArea = area(2.5);
std::cout << "Area of circle: " << circleArea << std::endl;

// Calculate volume of a cylinder


double cylinderVolume = area(2.5, 10);
std::cout << "Volume of cylinder: " << cylinderVolume << std::endl;

return 0;
}

c) Describe different types of inheritance.


ans:-nheritance is a fundamental concept in object-oriented programming (OOP) that
allows a class (called the derived class or subclass) to inherit properties and behavior
from another class (called the base class or superclass).
1.Single Inheritance:
In single inheritance, a derived class inherits from only one base class. This is the
simplest form of inheritance.
2.Multiple Inheritance:
In multiple inheritance, a derived class inherits from multiple base classes. This
allows the derived class to combine the properties and behavior of multiple base
classes.
3.Multilevel Inheritance:
In multilevel inheritance, a derived class inherits from another derived class, creating
a chain of inheritance. This forms a hierarchy of classes.
4.Hierarchical Inheritance:
In hierarchical inheritance, multiple derived classes inherit from a single base class.
Each derived class inherits the properties and behavior of the base class
independently.
5.Hybrid (Virtual) Inheritance:
Hybrid inheritance combines multiple types of inheritance, such as single, multiple,
and multilevel inheritance. Virtual inheritance is used to avoid ambiguities that can
arise from multiple inheritance.

d) Explain virtual base class with suitable diagram.


ans-
A virtual base class is a base class that is marked as virtual during inheritance. Virtual base
classes are used to resolve ambiguities and prevent multiple instances of the same base
class within a class hierarchy when using multiple inheritance.
Consider a scenario where you have a class hierarchy with multiple levels of inheritance and
multiple paths to a common base class.
+-----------+
| BaseClass |
+-----------+
/\
/ \
/ \
+------------------+------------------+
| DerivedClass1 | DerivedClass2 |
+------------------+------------------+
\ /
\ /
\ /
\ /
+-----------+
| Final |
+-----------+

e) Describe file manipulators with their syntaxes.


Manipulators are helping functions that can modify the input/output stream. It does not mean
that we change the value of a variable, it only modifies the I/O stream using insertion (<<)
and extraction (>>) operators.
Types of Manipulators There are various types of manipulators:

Manipulators without arguments: The most important manipulators defined by the IOStream
library are provided below.
endl: It is defined in ostream. It is used to enter a new line and after entering a new line it
flushes (i.e. it forces all the output written on the screen or in the file) the output stream.
ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.
ends: It is also defined in ostream and it inserts a null character into the output stream. It
typically works with std::ostrstream, when the associated output buffer needs to be null-
terminated to be processed as a C string.
flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output
written on the screen or in the file. Without flush, the output would be the same, but may not
appear in real-time. Examples:

1(Write a C++ program to copy contents of one file to another file.


ans:-#include <iostream>
#include <fstream>

int main() {
std::ifstream inputFile("input.txt"); // Open input file for reading
std::ofstream outputFile("output.txt"); // Open output file for writing
if (!inputFile.is_open()) {
std::cerr << "Error opening input file!" << std::endl;
return 1;
}

if (!outputFile.is_open()) {
std::cerr << "Error opening output file!" << std::endl;
return 1;
}

char ch;
while (inputFile.get(ch)) {
outputFile.put(ch);
}
inputFile.close();
outputFile.close();
std::cout << "File copied successfully!" << std::endl;
return 0;
}

b) Write a program to calculate area and circumference of a circle using inline


function.
ans_-#include <iostream>
inline double calculateArea(double radius) {
return 3.14 * radius * radius;
}inline double calculateCircumference(double radius) {
return 2 * 3.14 * radius;
}

int main() {
double radius; std::cout << "Enter the radius of the circle: ";
std::cin >> radius;s
double area = calculateArea(radius);
double circumference = calculateCircumference(radius);
std::cout << "Area of the circle: " << area << std::endl;
std::cout << "Circumference of the circle: " << circumference << std::endl;
return 0;
}

c) Declare a class of vehicle. Derived classes are two wheeler, three wheeler and four
wheeler. Display the properties of each type of vehicle using member functions of
class.
ans;_#include <iostream>
#include <string>

class Vehicle {
protected:
std::string type;

public:
Vehicle(std::string vehicleType) : type(vehicleType) {}

// Member function to display properties of the vehicle


virtual void display() {
std::cout << "Type of vehicle: " << type << std::endl;
}
};
class TwoWheeler : public Vehicle {
public:

TwoWheeler() : Vehicle("Two Wheeler") {}

// Override display function to include specific properties of Two Wheeler


void display() override {
std::cout << "Type of vehicle: " << type << std::endl;
std::cout << "Number of wheels: 2" << std::endl;
}
};
class ThreeWheeler : public Vehicle {
public:
// Constructor
ThreeWheeler() : Vehicle("Three Wheeler") {}

void display() override {


std::cout << "Type of vehicle: " << type << std::endl;
std::cout << "Number of wheels: 3" << std::endl;
}
};
// Derived class: FourWheeler
class FourWheeler : public Vehicle {
public:
FourWheeler() : Vehicle("Four Wheeler") {}
void display() override {
std::cout << "Type of vehicle: " << type << std::endl;
std::cout << "Number of wheels: 4" << std::endl;
}
};

int main() {
TwoWheeler twoWheeler;
ThreeWheeler threeWheeler;
FourWheeler fourWheeler;
std::cout << "Properties of Two Wheeler:" << std::endl;
twoWheeler.display();
std::cout << std::endl;

std::cout << "Properties of Three Wheeler:" << std::endl;


threeWheeler.display();
std::cout << std::endl;

std::cout << "Properties of Four Wheeler:" << std::endl;


fourWheeler.display();
std::cout << std::endl;

return 0;
}

d) Write a C++ program to use setfile () and setiosflags () manipulator.


ans-#include <iostream>
#include <iomanip>

int main() {
int number = 12345;

std::cout << "Using setfill() manipulator:" << std::endl;


std::cout << std::setfill('*') << std::setw(10) << number << std::endl;

std::cout << std::setfill(' '); // Reset fill character to default space

std::cout << "Using setiosflags() manipulator:" << std::endl;


std::cout << std::setiosflags(std::ios::left) << std::setw(10) << number << std::endl;
return 0;
}

5)Write a C++ program to compare two strings using overload operater

ans:-#include <iostream>
#include <string>

class MyString {
private:
std::string str;

public:
// Constructor
MyString(std::string s) : str(s) {}

bool operator==(const MyString& other) const {


return str == other.str;
}

std::string getString() const {


return str;
}
};

int main() {

MyString str1("Hello");
MyString str2("World");
MyString str3("Hello");

if (str1 == str2) {
std::cout << str1.getString() << " is equal to " << str2.getString() << std::endl;
} else {
std::cout << str1.getString() << " is not equal to " << str2.getString() << std::endl;
}

if (str1 == str3) {
std::cout << str1.getString() << " is equal to " << str3.getString() << std::endl;
} else {
std::cout << str1.getString() << " is not equal to " << str3.getString() << std::endl;
}

return 0;
}

b) Explain try, catch and throw in exception handling.


ans:-Try: The "try" block is used to enclose the code that might throw an exception.
It's essentially a guarded block of code. When an exception occurs within this block,
it is thrown, and the control is transferred to the catch block (if there's a matching
catch block).
Catch: The "catch" block follows the "try" block. It's used to handle exceptions that
are thrown within the "try" block. Each catch block specifies the type of exception it
can handle. If an exception of that type (or a subtype) is thrown within the try block,
control is transferred to the catch block. The catch block then executes its code to
handle the exception. If no matching catch block is found, the program will terminate
with an unhandled exception.
Throw: The "throw" statement is used to explicitly throw an exception within the try
block. It allows you to create custom exceptions or to rethrow exceptions caught in a
catch block. When you throw an exception, you specify the type of exception to be
thrown.)

Design C++ class which contain function display (). Write a program to count number
of times display () function is called (Use static data member)
#include <iostream>

class MyClass {
private:
static int displayCount; // Static data member to count function calls

public:
void display() {
std::cout << "Display function called." << std::endl;
displayCount++; // Increment the count each time the function is called
}

static int getDisplayCount() {


return displayCount; // Return the count of function calls
}
};

int MyClass::displayCount = 0; // Initialize the static data member

int main() {
MyClass obj1, obj2, obj3;

obj1.display();
obj2.display();
obj3.display();
std::cout << "Display function was called " << MyClass::getDisplayCount() << " times." <<
std::endl;

return 0;
}

.A destructor in C++ is a special member function of a class that is called


automatically when an object of that class goes out of scope or is explicitly deleted.
Its name is the same as the class name but prefixed with a tilde (~).

Here's why destructors are important:

Resource Deallocation: Destructors are crucial for releasing resources acquired by an


object during its lifetime. This includes deallocating memory, closing files, releasing
network connections, etc. Without a destructor, resources could be leaked, leading to
memory or resource exhaustion.
Clean-up Tasks: Destructors allow for the execution of clean-up tasks necessary for
the proper shutdown of an object. This can include releasing locks, closing database
connections, or any other finalization tasks.
Scope Management: Destructors ensure that resources are properly released even in
the presence of exceptions or premature
#include <iostream>

class Resource {
public:
Resource() {
std::cout << "Resource acquired." << std::endl;
}

~Resource() {
std::cout << "Resource released." << std::endl;
}
};

int main() {
Resource res;
return 0;
}

e) What is tokens in C++? Explain in detail.


ans:-a token is the smallest unit of a program that has a meaning. When you write a program
in C++, you use various elements such as keywords, identifiers, literals, operators,
punctuation symbols, and special symbols. Each of these elements is considered a token.

Let's break down the different types of tokens in C++:


Keywords: Keywords are reserved words in C++ that have predefined meanings and cannot
be used for any other purpose. Examples include int, if, else, while, class, etc.
Identifiers: Identifiers are names given to various program elements such as variables,
functions, classes, etc. They consist of letters, digits, and underscores, and must begin with
a letter or an underscore. Identifiers are case-sensitive.
Literals: Literals are constant values that are used directly in the program. There are different
types of literals in C++, including:
Integer literals: Whole numbers, such as 42.
Floating-point literals: Decimal numbers, such as 3.14.
Character literals: Single characters enclosed in single quotes, such as 'a'.
String literals: Sequences of characters enclosed in double quotes, such as "Hello, world!".
Boolean literals: true and false.
Operators: Operators perform operations on operands. They include arithmetic operators (+,
-, *, /, %), relational operators (==, !=, <, >, <=, >=), logical operators (&&, ||, !), assignment
operators (=, +=, -=, *=, /=), etc.
Punctuation Symbols: Punctuation symbols are used to structure the code and include
symbols such as semicolons (;), commas (,), colons (:), parentheses (()), braces ({}), and
brackets ([]).
Special Symbols: Special symbols include preprocessor directives (#include, #define, etc.),
scope resolution operator (::),

a) Call-by-value and call-by-reference


Call-by-Value:
In call-by-value, a copy of the actual argument is passed to the function.
The function works with the copy of the data, not the original data itself.
Any modifications made to the parameters inside the function do not affect the original data
outside the function.
Call-by-Reference:
In call-by-reference, instead of passing a copy of the actual argument, a reference to the
original data is passed to the function.
Any changes made to the parameters inside the function directly affect the original data
outside the function.b) Data abstraction

Data abstraction is a fundamental concept in object-oriented programming (OOP) that


refers to the process of hiding the implementation details of a class and exposing
only the essential features of the object. In other words, it allows the programmer to
focus on what an object does rather than how it does it. Data abstraction is achieved
through the use of classes and access specifiers.

c) Default Argument
A default argument is a value provided in a function declaration that is automatically used if
the caller of the function doesn't provide a corresponding argument. Default arguments are
particularly useful when you want to provide a convenient default value for a function
parameter but also want to allow callers to override that value if necessary.

You might also like