Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Data Structure

The document provides a comprehensive overview of key concepts in C++ programming, including encapsulation, binding types, inline functions, streams, friend functions, constructors, inheritance, and exception handling. It explains various operators, memory management, user-defined data types, and formatted input/output functions, along with examples for clarity. Additionally, it covers advanced topics such as class templates, virtual base classes, and the importance of destructors.

Uploaded by

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

Data Structure

The document provides a comprehensive overview of key concepts in C++ programming, including encapsulation, binding types, inline functions, streams, friend functions, constructors, inheritance, and exception handling. It explains various operators, memory management, user-defined data types, and formatted input/output functions, along with examples for clarity. Additionally, it covers advanced topics such as class templates, virtual base classes, and the importance of destructors.

Uploaded by

Suraj Tapkir
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

2 mark

1) What is Encapsulation?

Ans= Encapsulation is an OOP principle where the implementation details of a class are hidden from
the outside world. It ensures that the data (attributes) and the methods (functions) are bundled
together and the data can only be accessed or modified through well-defined methods, providing
data protection.

2) Define the following terms i) Early Binding ii) Late Binding

Ans= i) Early Binding: Early Binding (or Static Binding) is the process where method calls are resolved
at compile-time. The method address is determined before the program is run.

ii) Late Binding: Late Binding (or Dynamic Binding) occurs when the method call is resolved at
runtime, not at compile-time. This is typically used with virtual functions in C++.

3) What is Inline function?

Ans= An inline function is a function where the compiler attempts to insert the function’s code
directly into the place where it is called, instead of performing a normal function call. This can help
reduce the overhead of function calls.

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

Ans=  get(): Used to read input from streams (such as from cin or files).

 put(): Used to write output to streams (such as to cout or files).

5) What is stream?

Ans= A stream is an abstraction that represents a flow of data, either from input to output (like
reading from a file or keyboard) or from output to input (like writing to a file or display). Streams are
used for handling I/O operations in C++.

6) Define Friend function.

Ans= A friend function in C++ is a function that is not a member of a class but has access to its private
and protected members. It is defined outside the class but declared as a friend inside the class.

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

Ans= perator, state the syntax: The new operator is used to allocate memory dynamically on the
heap. It returns a pointer to the allocated memory.

 Syntax: pointer = new dataType;

8) State the need of virtual keyword.

Ans= he virtual keyword is used to tell the compiler to support dynamic (or late) binding. It ensures
that the correct method is called for an object, even when you use a pointer or reference to a base
class.
9) State user defined data types in C++.

Ans= The user-defined data types in C++ include:

 Class: A blueprint for creating objects.

 Struct: A collection of different data types.

 Union: A data structure that allows storing different data types in the same memory location.

 Enum: A user-defined type that consists of integral constants.

10) Explain the use of Scope Resolution operator

Ans= the scope resolution operator :: is used to define a method or variable outside the class. It is
also used to access global variables and functions when there is a local variable with the same name.

11) What is extraction and insertion operator?

Ans=  Extraction Operator (>>): Used to read data from input streams (e.g., cin).

 Insertion Operator (<<): Used to write data to output streams (e.g., cout).

12) Explain any two manipulators.

Ans=  endl: Used to insert a newline character and flush the output buffer.

 setw(n): Used to set the width of the next output to n characters.

13) Define constructor..

Ans= A constructor is a special member function of a class that is called automatically when an object
of the class is created. It initializes the object with default or user-defined values.

14) What is reference variable? What is its major use.

Ans=A reference variable is an alias for an already existing variable. It is used to directly access the
memory location of another variable. The major use is to avoid copying large objects and to modify
the original variable through the reference

16) What is compile - Time polymorphism.

Ans=Compile-time polymorphism is the method resolution that happens during the compilation
process, and it's generally achieved using method overloading and operator overloading.

17) What is default argument.

Ans= A default argument is a value that is assigned to a function's parameter if no argument is


provided during the function call. It allows functions to be called with fewer arguments.

18) What are the access specifiers used in C++

Ans=  public: Members are accessible from outside the class.

 private: Members are not accessible from outside the class.

 protected: Members are accessible within the class and by derived classes

4 mark
1) List different types of constructor. Explain any one constructor with example.

Ans= Types of Constructors:

 Default Constructor: A constructor that doesn't take any parameters.

 Parameterized Constructor: A constructor that takes parameters to initialize data members.

 Copy Constructor: A constructor that creates a new object as a copy of an existing object.

Example:

class Box {

private:

int length, width;

public:

// Default Constructor

Box() {

length = 0;

width = 0;

// Parameterized Constructor

Box(int l, int w) {

length = l;

width = w;

void display() {

cout << "Length: " << length << ", Width: " << width << endl;

};

int main() {

Box box1; // Calls default constructor

Box box2(5, 10); // Calls parameterized constructor

box1.display();

box2.display();

return 0;}

2) What is function overloading? Explain with suitable example.


Ans= Function Overloading is a feature in C++ where multiple functions with the same name can
exist in the same scope but with different parameters (either in number or type). The appropriate
function is selected based on the argument list.

Example: class Printer {

public:

void print(int i) {

cout << "Printing integer: " << i << endl;

void print(double d) {

cout << "Printing double: " << d << endl;

};

int main() {

Printer p;

p.print(5); // Calls print(int)

p.print(3.14); // Calls print(double)

return 0;

3) Describe different types of inheritance.

Ans= Types of Inheritance:

 Single Inheritance: A class inherits from one base class.

 Multiple Inheritance: A class inherits from more than one base class.

 Multilevel Inheritance: A class inherits from another class, which in turn inherits from
another class.

 Hierarchical Inheritance: Multiple classes inherit from the same base class.

 Hybrid Inheritance: A combination of two or more types of inheritance.

4) Explain virtual base class with suitable diagram.


Ans= Virtual Base Class is used in multiple inheritance to avoid ambiguity when a derived class has
more than one path to access a common base class. It ensures only one instance of the base class is
created.

Diagram: BaseClass (virtual)

/ \

Derived1 Derived2

\ /

Derived3

5) Describe file manipulators with their syntaxes

Ans= File manipulators are used in C++ to modify the behavior of input and output streams,
especially when working with files.

 Syntax for File Manipulators:

o setw(n) – Sets the width of the output field to n characters.

#include <iostream>

#include <iomanip>

int main() {

int num = 42;

std::cout << std::setw(10) << num; // Outputs ' 42'

o setprecision(n) – Sets the number of decimal places in floating-point numbers.

std::cout << std::setprecision(4) << 3.14159; // Outputs 3.142

o setiosflags() – Used to set a specific flag.

std::cout << std::setiosflags(std::ios::fixed); // Fixed point notation

o flush – Forces the output buffer to be written to the stream.

std::cout << "Hello" << std::flush; // Forces immediate output

6) Explain memory management operators with the help of suitable example.


Ans= C++, memory management operators are used to allocate and deallocate memory.

 Syntax:

o new – Allocates memory on the heap.

int* p = new int; // Allocates memory for an integer

*p = 10;

o delete – Deallocates memory allocated by new.

delete p; // Frees the memory allocated

o new[] – Allocates memory for an array.

int* arr = new int[5]; // Allocates memory for an array of 5 integers

o delete[] – Deallocates memory allocated for an array.

delete[] arr; // Frees the memory allocated for the array

7) Explain memory allocation for objects with non-static data member and static data member.

Ans= In C++, memory allocation for non-static data members occurs separately for each object of a
class. Each time an object is created, new memory is allocated for its non-static members.

However, static data members are shared across all objects of a class. They are allocated only once,
at class level, and not per object. Memory for static members is allocated in the data segment, not
with object memory.

Example: class Sample {

int a; // non-static

static int count; // static

};

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


Ans:
Tokens are the smallest individual units in a C++ program. Types include:

1. Keywords: Reserved words (e.g., int, class, if)

2. Identifiers: Names for variables, functions, etc.

3. Constants: Fixed values (e.g., 5, 3.14)

4. Operators: Symbols that perform operations (e.g., +, =)

5. Punctuation/Special symbols: ;, {}, (), []

6. Strings: Sequence of characters in double quotes (e.g., "Hello")

8) When do we make a class virtual base class? Explain it with suitable example.
Ans=A class is made a virtual base class to avoid duplication of data members during multiple
inheritance when a common base class is inherited multiple times.

Example:

class A {

public:

int x;

};

class B : virtual public A {};

class C : virtual public A {};

class D : public B, public C {};

int main() {

D obj;

obj.x = 10; // No ambiguity due to virtual inheritance

10) Explain any four formatted input/output functions.


Ans:
Formatted I/O functions provide control over input and output format. Common functions include:

1. setw(n): Sets the width of the next output field.

cout << setw(10) << "Hello";

2. setprecision(n): Sets the number of digits to be displayed for floating-point numbers.

cout << setprecision(2) << 12.3456; // Output: 12

3. setfill(ch): Fills the empty space with a character.

cout << setfill('*') << setw(5) << 12; // Output: ***12

4. setiosflags(flag): Sets format flags like fixed, showpoint, etc.

cout << setiosflags(ios::fixed) << setprecision(2) << 3.14159;

9) Explain array of objects in C++ with example.


Ans:
An array of objects in C++ is used when you want to handle multiple instances of a class using an
array structure.

Example: class Student {

public:

int id;

void getData() {

cout << "Enter ID: ";

cin >> id;

void showData() {

cout << "ID: " << id << endl;

};

int main() {

Student s[3]; // array of 3 Student objects

for(int i = 0; i < 3; i++) {

s[i].getData();

for(int i = 0; i < 3; i++) {

s[i].showData();

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


Ans:
In C++, exception handling is used to handle runtime errors using three keywords:
 try: Wraps code that might throw an exception.

 throw: Used to throw an exception.

 catch: Catches and handles the thrown exception.

Example: #include <iostream>

using namespace std;

int main() {

int a, b;

cout << "Enter two numbers: ";

cin >> a >> b;

try {

if (b == 0)

throw "Division by zero error!";

cout << "Result: " << a / b << endl;

catch (const char* msg) {

cout << "Exception: " << msg << endl;

return 0;

23) What is Destructor? State the importance of destructor with example.


Ans:
A destructor is a special member function that is automatically called when an object goes out of
scope. It is used to release resources like memory, files, etc.
 Destructor has the same name as the class, preceded by ~.

 It takes no arguments and has no return type.

 Only one destructor is allowed per class.

Example: #include <iostream>

using namespace std;

class Demo {

public:

Demo() {

cout << "Constructor called" << endl;

~Demo() {

cout << "Destructor called" << endl;

};

int main() {

Demo d;

return 0;

25) Explain various stream classes used to perform console input/output (I/O) operations.
Ans:
C++ uses stream classes for I/O:

 istream: For input from standard input (cin)

 ostream: For output to standard output (cout)


 iostream: Supports both input and output

 ifstream: For file input

 ofstream: For file output

 fstream: For both input and output on files

These classes provide functions and operators for formatted and unformatted I/O.

26) What is class Template? Explain syntax of class template with suitable example.
Ans:
Templates allow creation of classes or functions that work with any data type.

Syntax:

template <class T>

class MyClass {

T a;

public:

void set(T x) { a = x; }

void show() { cout << "Value: " << a << endl; }

};

int main() {

MyClass<int> obj1;

obj1.set(10);

obj1.show();

MyClass<string> obj2;

obj2.set("Hello");

obj2.show()

return 0;

3-Mark Questions:

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

 Call-by-value: Copies value of actual arguments; changes do not affect originals.

 Call-by-reference: Passes address; changes affect actual arguments.

b) Data abstraction
 Hides internal details and shows only essential features.

 Achieved using classes and access specifiers.

c) Default Argument

 Provides default values to parameters in function declaration.

void show(int x, int y = 10);

a) Exception Handling

 Mechanism to handle runtime errors using try, catch, and throw.

b) Operator Overloading

 Redefining an operator to work with user-defined types (like objects).

 Done using operator keyword.

c) Pointer to object with example

 A pointer that holds the address of an object.

class A {

public:

void show() { cout << "Hello"; }

};

int main() {

A obj, *ptr = &obj;

ptr->show();

You might also like