C++ Programming Basic Q&A

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Q & A for C++

Question of 2 number-
1. Why an inline function is used?
Ans- Inline functions in C++ are used to reduce the function call overhead. When a
function is defined as inline, the compiler replaces the function call with the function
code itself, eliminating the overhead of pushing the function parameters onto the
stack, jumping to the function body, and then returning. Inline functions can improve
performance for small, frequently used functions. They are often used in header-
only libraries to avoid multiple definition errors, and they are suitable for short,
frequently used functions and template functions.
2. Draw the form of Hybrid inheritance?
Ans- Hybrid inheritance is a combination of more than one type of inheritance. It can
be any combination of the different types of inheritance, such as single inheritance,
multiple inheritance, multilevel inheritance, and hierarchical inheritance. One of the
common forms of hybrid inheritance is shown below:

```
A A
/\ /\
/ \ / \
B C B C
\ / \ /
\/ \/
D D
```

In the above diagram:


- Classes A, B, and C are inherited using multiple inheritances.
- Class D is inherited using multilevel inheritance.

Here's how the code would look in C++:

```cpp
#include <iostream>
using namespace std;

// Base class
class A {
public:
void displayA() {
cout << "Class A" << endl;
Q & A for C++

}
};

// Derived class 1
class B: public A {
public:
void displayB() {
cout << "Class B" << endl;
}
};

// Derived class 2
class C: public A {
public:
void displayC() {
cout << "Class C" << endl;
}
};

// Derived class 3
class D: public B, public C {
public:
void displayD() {
cout << "Class D" << endl;
}
};

int main() {
// Creating object of derived class D
D objD;

// Accessing members
objD.displayA(); // Class A
objD.displayB(); // Class B
objD.displayC(); // Class C
objD.displayD(); // Class D

return 0;
}
```
3. Name the stream classes for console operator?
Q & A for C++

Ans- In C++, the Standard Library provides the following stream classes for console
input and output:

1. **`iostream`**:
- **`cin`**: Standard input stream object.
- **`cout`**: Standard output stream object.

Here is a simple example of using `cin` and `cout`:

```cpp
#include <iostream>
using namespace std;

int main() {
int number;

// Output to console
cout << "Enter a number: ";

// Input from console


cin >> number;

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

return 0;
}
```

In this example, `cin` is used to get input from the user, and `cout` is used to output
to the console.
4. Write the syntax of switch( ) statement.
Ans- Here is the syntax of the switch statement in C++:
switch (expression) {
case constant1:
// Statements to be executed if expression == constant1
break;
case constant2:
// Statements to be executed if expression == constant2
break;
.
Q & A for C++

.
.
case constantN:
// Statements to be executed if expression == constantN
break;
default:
// Statements to be executed if expression doesn't match any case
}
5. What are the float expression?
Ans- Float expressions in C++ refer to expressions that evaluate to floating-point
numbers. Here are some examples:

1. **Literal Float Values**:


```cpp
float number1 = 3.14; // Literal float value
float number2 = 2.5f; // Literal float value (suffix 'f' to specify it's a float)
```

2. **Arithmetic Operations**:
```cpp
float result = 5.0 + 2.5; // Addition of two float values
float result2 = 10.0 / 2.0; // Division of two float values
```

3. **Variables**:
```cpp
float length = 4.5;
float width = 2.0;
float area = length * width;
```

4. **Function Return Values**:


```cpp
float sqrt_result = sqrt(25.0); // Square root function returning float value
```

5. **Type Casting**:
```cpp
int integer_number = 10;
float float_number = static_cast<float>(integer_number); // Type casting int to
float
Q & A for C++

```

6. **Array Elements**:
```cpp
float float_array[5] = {3.5, 4.0, 6.25, 1.1, 5.6};
```

7. **Expressions involving floats**:


```cpp
float result = (5.0 * 2.0) / (1.5 + 0.5);
```
6. Expression x<<4 will shift how many bits position and in which direction?
Ans- The expression `x << 4` will shift the bits in variable `x` four positions to the left.
This operation is known as a left shift operation.

- **Direction**: The bits are shifted towards the left.

- **Number of Bits Shifted**: Four positions to the left.

Here is an example:

```cpp
#include <iostream>
using namespace std;

int main() {
int x = 5; // x is 0000 0101 in binary

// Shifting x four positions to the left


int result = x << 4; // result will be 0001 0100 in binary, which is 80 in decimal

cout << "x shifted 4 positions to the left: " << result << endl;

return 0;
}
```

Output:
```
x shifted 4 positions to the left: 80
```
Q & A for C++

In binary:

```
x : 0000 0101
Result : 0001 0100
```
7. What is pointer?
8. Write the format of accessing the class member .
Ans- The format for accessing a class member in C++ using the dot (`.`) operator is as
follows:

```cpp
objectName.memberName;
```

Where:
- `objectName`: Name of the object of the class.
- `memberName`: Name of the member variable or member function.

Here is a simple example:

```cpp
#include <iostream>
using namespace std;

class MyClass {
public:
int myVariable;

void myFunction() {
cout << "This is a member function." << endl;
}
};

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

// Accessing member variable


obj.myVariable = 10;
cout << "Value of myVariable: " << obj.myVariable << endl;
Q & A for C++

// Accessing member function


obj.myFunction();

return 0;
}
```

Output:
```
Value of myVariable: 10
This is a member function.
```

In the above example:


- `obj.myVariable` is accessing the member variable `myVariable` of the object `obj`.
- `obj.myFunction()` is calling the member function `myFunction()` of the object
`obj`.
9. Write the syntax catch () handler.
Ans- The syntax for a `catch` block in C++ is as follows:

```cpp
try {
// code that may throw an exception
}
catch (ExceptionType1 parameter1) {
// Exception handler for ExceptionType1
// Code to handle the exception
}
catch (ExceptionType2 parameter2) {
// Exception handler for ExceptionType2
// Code to handle the exception
}
catch (...) {
// Default exception handler
// Code to handle any other type of exception
}
```

- `try`: The `try` block contains the code where an exception might occur.
- `catch`: The `catch` block catches and handles exceptions thrown in the `try` block.
Q & A for C++

- `ExceptionType1`, `ExceptionType2`: Specific types of exceptions that the `catch`


block can handle.
- `parameter1`, `parameter2`: Parameters to hold the information about the
exception.
- `...`: The ellipsis `...` catch block is used to catch any type of exception that is not
caught by the preceding `catch` blocks.

Here's a simple example:

```cpp
#include <iostream>
using namespace std;

int main() {
int a = 10, b = 0, result;

try {
if (b == 0) {
throw "Division by zero error";
}

result = a / b;
cout << "Result: " << result << endl;
}
catch (const char* error) {
cerr << "Exception: " << error << endl;
}

return 0;
}
```

In this example:
- The `try` block checks for the condition `b == 0`.
- Since `b == 0`, it throws an exception.
- The `catch` block catches the exception and handles it.

10. What is destructor?


Ans- C++ is an object oriented programming (OOP) language which provides a special
member function called destructor which is used to destroy the objects when it is no
longer required. Declaration of destructor function is similar to that of constructor
Q & A for C++

function. The destructor’s name should be exactly the same as the name of
constructor; however it should be preceded by a tilde (~). For example if the class
name is student then the prototype of the destructor would be ~ student ().
11. Define the following terms with example.
a. Destructor
Ans- C++ is an object oriented programming (OOP) language which provides a
special member function called destructor which is used to destroy the
objects when it is no longer required. Declaration of destructor function is
similar to that of constructor function. The destructor’s name should be
exactly the same as the name of constructor; however it should be preceded
by a tilde (~). For example if the class name is student then the prototype of
the destructor would be ~ student ().

b. Dangling pointer
Ans- A dangling pointer in C++ is a pointer that continues to point to a
memory location after the memory has been deallocated (freed). Accessing
the memory location to which the dangling pointer points can lead to
unpredictable behavior, including program crashes, data corruption, and
security vulnerabilities. Dangling pointers typically occur when memory is
deallocated, but the pointer to that memory is not set to nullptr (NULL), or
when a pointer goes out of scope but is not set to nullptr.

Here's an example illustrating a dangling pointer:

```cpp
#include <iostream>
using namespace std;

int main() {
int* ptr = new int; // Dynamically allocate memory
*ptr = 5; // Assign value 5 to the allocated memory

// Deallocate the memory


delete ptr;

// ptr is now a dangling pointer


// Accessing *ptr after deallocation results in undefined behavior
cout << *ptr << endl; // Accessing the memory location pointed by ptr

return 0;
}
```

To prevent a pointer from becoming a dangling pointer, always set it to


nullptr (NULL) after deallocating the memory:

```cpp
Q & A for C++

#include <iostream>
using namespace std;

int main() {
int* ptr = new int; // Dynamically allocate memory
*ptr = 5; // Assign value 5 to the allocated memory

// Deallocate the memory


delete ptr;
ptr = nullptr; // Set ptr to nullptr to prevent it from becoming a dangling
pointer

// Now, accessing *ptr is safe as it is not pointing to any memory location


cout << *ptr << endl; // Accessing the memory location pointed by ptr

return 0;
}
```

Dangling pointers can also occur with stack-allocated variables when a


pointer outlives the variable it points to:

```cpp
#include <iostream>
using namespace std;

int* createInt() {
int localVar = 10;
int* ptr = &localVar;
return ptr; // returning a pointer to a local variable
}

int main() {
int* ptr = createInt();
cout << *ptr << endl; // Accessing a dangling pointer
return 0;
}
```

To avoid creating dangling pointers, always ensure that pointers are pointing
to valid memory locations. When a memory block is deallocated, set the
pointer to nullptr to indicate that it no longer points to a valid memory
location.
c. Arrays
Ans-
 An array is defined as the collection of similar type of data items
stored at contiguous memory allocation.
Q & A for C++

Array can store the primitive type of data such as int, char, float,
double etc and can also stored user defined data type like structure
and pointer.
 In ordered to be stored together in a single array all the elements
should be of same data type.
 The element are stored from left to right with the left most index
being the 0th index and the right most index being the (n-1)th index.
d. Static class
Ans- In C++, there is no concept of a "static class" like in some other
languages. However, you can create a class with only static members, which
effectively behaves like a static class. A class with only static members is
often used as a namespace for related utility functions or constants.

Here's an example:

#include <iostream>
using namespace std;

class Math {
public:
// Static member function
static int add(int a, int b) {
return a + b;
}

static int multiply(int a, int b) {


return a * b;
}

// Static member variable


static const double PI;
};

// Definition of static member variable


const double Math::PI = 3.14159;

int main() {
// Accessing static member function
cout << "Addition: " << Math::add(5, 3) << endl;
cout << "Multiplication: " << Math::multiply(5, 3) << endl;

// Accessing static member variable


cout << "Value of PI: " << Math::PI << endl;

return 0;
}
```
Q & A for C++

In the example above, the `Math` class contains only static member functions
and a static member variable. You access these members using the scope
resolution operator `::`, without needing to create an instance of the class.
This usage is similar to how static classes are used in other programming
languages.
e. Friend function
Ans- In C++, a friend function is a function that is not a member of a class but
has access to the class's private and protected members. It is declared in the
class with the keyword `friend`.

Here's an example of how a friend function is used:

#include <iostream>
using namespace std;

// Forward declaration of the class


class MyClass;

// Declaration of the friend function


void display(const MyClass &obj);

// MyClass class definition


class MyClass {
private:
int num;

public:
// Constructor
MyClass(int n) : num(n) {}

// Declaration of the friend function


friend void display(const MyClass &obj);
};

// Definition of the friend function


void display(const MyClass &obj) {
cout << "The private member of MyClass is: " << obj.num << endl;
}

int main() {
MyClass obj(5);
display(obj); // Calling the friend function
return 0;
}
```
Q & A for C++

In this example:
- `display()` is a friend function of the `MyClass` class.
- `display()` function is not a member of the `MyClass` class, but it can access
the private member `num` of the `MyClass`.
- `display()` function is able to access the private member `num` directly
without the need for getter methods because it is declared as a friend
function inside the class.

f. Call by value
Ans- Call by value is a parameter passing mechanism in C++ where the actual
value of an argument is passed to the function parameter. The function
works with the copy of the data, and any changes made to the parameter
inside the function do not affect the original data.

Here's an example:

#include <iostream>
using namespace std;

// Function definition
void changeValue(int x) {
x = 20; // Changing the value of the parameter
cout << "Inside the function, x = " << x << endl;
}

int main() {
int num = 10;

// Calling the function


changeValue(num); // Passing 'num' by value

// Original value remains unchanged


cout << "Outside the function, num = " << num << endl;

return 0;
}
```

Output:
```
Inside the function, x = 20
Outside the function, num = 10
```

In this example:
- `changeValue()` function takes an integer parameter by value.
Q & A for C++

- When the function is called with `num`, the value of `num` (10) is copied
into the parameter `x`.
- Inside the function, the value of `x` is changed to 20, but this change does
not affect the original value of `num` outside the function.
- Thus, the original value of `num` remains unchanged.

g. Polymorphism
Ans- Ans- Polymorphism, in the context of object-oriented programming,
refers to the ability of different classes to be treated as objects of a common
superclass. There are two types of polymorphism in C++: compile-time
(static) polymorphism and run-time (dynamic) polymorphism.

1. **Compile-Time Polymorphism (Static Polymorphism)**:


- **Function Overloading**: Multiple functions can have the same name
but different parameter lists. The compiler selects the appropriate function
to call based on the arguments' number, types, and order.
- **Operator Overloading**: Operators can be overloaded to provide
special meaning to the user-defined data types. It allows a way to redefine
the way the operator behaves with a specific data type.

Example of Function Overloading:

#include <iostream>
using namespace std;

class Example {
public:
void display(int i) {
cout << "Integer: " << i << endl;
}
void display(double d) {
cout << "Double: " << d << endl;
}
};

int main() {
Example obj;
obj.display(5); // Calls the first display function
obj.display(5.5); // Calls the second display function
return 0;
}
```

2. **Run-Time Polymorphism (Dynamic Polymorphism)**:


- **Virtual Functions and Late Binding (Function Overriding)**: It is the
ability of the derived class to provide a specific implementation of a function
Q & A for C++

that is already provided by its base class. The function to be called is


determined at run-time.
- **Abstract Classes and Pure Virtual Functions**: An abstract class is a
class that has at least one pure virtual function. It is a class that cannot be
instantiated and is designed to be subclassed.

Example of Virtual Functions and Late Binding:

#include <iostream>
using namespace std;

// Base class
class Animal {
public:
// Virtual function
virtual void sound() {
cout << "Animal sound" << endl;
}
};

// Derived class
class Dog : public Animal {
public:
// Override the sound method
void sound() {
cout << "Dog barks" << endl;
}
};

int main() {
Animal *animal;
Dog dog;
animal = &dog;

// Virtual function call


animal->sound(); // Output: Dog barks

return 0;
}
```

In this example, the `sound()` function is a virtual function. It is defined in the


base class `Animal` and is overridden in the derived class `Dog`. At runtime,
the `sound()` function of `Dog` class is called, demonstrating the late binding
feature of run-time polymorphism.

h. Pure virtual function


Q & A for C++

Ans- A pure virtual function in C++ is a virtual function that has no definition
within the base class and must be implemented in derived classes. It is
declared by assigning 0 to the function.

Here's an example:

#include <iostream>
using namespace std;

// Base class
class Shape {
public:
// Pure virtual function
virtual void draw() = 0;
};

// Derived class
class Circle : public Shape {
public:
// Override the pure virtual function
void draw() {
cout << "Drawing Circle" << endl;
}
};

// Derived class
class Rectangle : public Shape {
public:
// Override the pure virtual function
void draw() {
cout << "Drawing Rectangle" << endl;
}
};

int main() {
Circle circle;
Rectangle rectangle;

// Using polymorphism to call the draw function


Shape *shape1 = &circle;
Shape *shape2 = &rectangle;

shape1->draw(); // Output: Drawing Circle


shape2->draw(); // Output: Drawing Rectangle

return 0;
}
Q & A for C++

```

In this example, `Shape` is an abstract base class with a pure virtual function
`draw()`. The derived classes `Circle` and `Rectangle` implement this function.
You cannot create an instance of the base class `Shape`, but you can create
pointers of type `Shape` and use polymorphism to call the draw function on
the derived classes.
i. Inheritance
Ans- Inheritance is a prime feature of object oriented programming language.
It is process by which new classes called derived classes(sub classes,
extended classes, or child classes) are created from existing classes called
base classes(super classes, or parent classes). The derived class inherits all
the features (capabilities) of the base class and can add new features specific
to the newly created derived class. The base class remains unchanged. We
can say that re-usability is concerned as to how we can use a system or its
part in other systems. 7 Inheritance is a technique of organizing information
in a hierarchical form. It is a Inheritance relation between classes that allows
for definition and implementation of one class based on the definition of
existing classes.
j. Generalization
Ans- Generalization, in the context of object-oriented programming, is the
process of forming a new class from one or more existing classes by taking
common features from them. It is the process of extracting shared
characteristics from two or more classes, and combining them into a
generalized superclass. Generalization is a fundamental concept in
inheritance.

Here's an example to illustrate generalization:

```cpp
#include <iostream>
using namespace std;

// Base class
class Animal {
public:
void eat() {
cout << "Animal eats" << endl;
}
void sleep() {
cout << "Animal sleeps" << endl;
}
};

// Derived class
class Dog : public Animal {
public:
Q & A for C++

void bark() {
cout << "Dog barks" << endl;
}
};

// Derived class
class Cat : public Animal {
public:
void meow() {
cout << "Cat meows" << endl;
}
};

int main() {
Dog dog;
Cat cat;

// Using inherited functions


dog.eat(); // Output: Animal eats
cat.eat(); // Output: Animal eats

dog.sleep(); // Output: Animal sleeps


cat.sleep(); // Output: Animal sleeps

// Using derived functions


dog.bark(); // Output: Dog barks
cat.meow(); // Output: Cat meows

return 0;
}
```

In this example, `Animal` is the base class, and `Dog` and `Cat` are derived
classes. The `eat()` and `sleep()` functions are generalizations as they are
common to both `Dog` and `Cat`. These functions are inherited from the
`Animal` class. The `bark()` function is specific to the `Dog` class, and the
`meow()` function is specific to the `Cat` class.
12. Explain link and association.
Ans- In object-oriented modeling, "link" and "association" are terms used to describe
relationships between classes.

Association:
Association is a relationship between two or more classes. It represents how objects
of these classes are related to each other.
It is a bi-directional relationship.
Associations can be one-to-one, one-to-many, or many-to-many.
Q & A for C++

The association relationship can be shown using a line connecting the classes. You
can also add multiplicity, role names, and navigation arrows to specify the
association.
Example:

cpp
Copy code
class Person; // Forward declaration

class Car {
private:
string model;
public:
Car(string model) : model(model) {}
string getModel() { return model; }
};

class Person {
private:
string name;
Car* car;
public:
Person(string name, Car* car) : name(name), car(car) {}
string getName() { return name; }
Car* getCar() { return car; }
};

int main() {
Car car("Toyota Corolla");
Person person("John", &car);

cout << person.getName() << " owns a " << person.getCar()->getModel() << endl;

return 0;
}
Link:
A link represents a connection or relationship between objects of different classes.
In simple terms, it's an instance of an association.
Links are concrete instances of an association relationship.
For example, if we take the same classes Car and Person, a link would represent a
particular Person owning a particular Car.
Example:

cpp
Copy code
class Person; // Forward declaration
Q & A for C++

class Car {
private:
string model;
public:
Car(string model) : model(model) {}
string getModel() { return model; }
};

class Person {
private:
string name;
Car* car;
public:
Person(string name, Car* car) : name(name), car(car) {}
string getName() { return name; }
Car* getCar() { return car; }
};

int main() {
Car car("Toyota Corolla");
Person person("John", &car);

cout << person.getName() << " owns a " << person.getCar()->getModel() << endl;

return 0;
}
In this example, there is an association between the Person and Car classes. The
Person class has a member of type Car*, representing the association between a
person and a car. In the main function, an instance of Person (John) is associated
with an instance of Car (Toyota Corolla) through a link.
13. What is meta data?
Ans- **Metadata** is data that describes other data. It provides information about
the characteristics of data such as:
- How it is formatted
- When it was created
- Who created it
- How it is accessed and used

In software development, metadata is used to provide documentation, classification,


and context to data. Metadata can be found in various contexts, including databases,
websites, and file systems.

For example:
- In a file system, metadata includes the file name, size, creation date, and
permissions.
- In a database, metadata might include the data types of the fields, the length of the
fields, and whether the field can accept null values.
Q & A for C++

- In a website, metadata might include keywords, description, and author


information.

In short, metadata is data about data, providing context, definition, and structure to
the primary data.

14. What do you meant by event and states?


Ans- In the context of programming and systems, "event" and "state" are
fundamental concepts:

### Event:
- An **event** is an occurrence that triggers some activity or process. It could be a
user action, such as a mouse click, a keypress, or a system occurrence, like a timer
expiration or a message arrival.
- In programming, events often refer to interactions between the user and the
program. When a program is designed to respond to specific actions by the user,
these actions are referred to as events.
- Events can trigger transitions between different states in a system.

### State:
- A **state** represents a situation or condition at a specific point in time during the
execution of a program or the operation of a system.
- A system can be in one of many possible states at any given time.
- State management is crucial in programming, especially in the context of state
machines and event-driven systems.

### Example:
Consider a simple light switch:
- **States**: The light can be in two states: On or Off.
- **Events**: Pressing the switch (turning on or off) is the event that causes the
state to change.

### Example of Event and State in C++:


```cpp
#include <iostream>
using namespace std;

// Enum representing the states of the light


enum class LightState {
ON,
OFF
};

// Class representing the light


class Light {
private:
LightState state;
Q & A for C++

public:
// Constructor
Light() : state(LightState::OFF) {}

// Function to get the current state of the light


LightState getState() {
return state;
}

// Function to handle the event of pressing the switch


void pressSwitch() {
if (state == LightState::ON) {
state = LightState::OFF;
cout << "The light is now OFF" << endl;
} else {
state = LightState::ON;
cout << "The light is now ON" << endl;
}
}
};

int main() {
Light light;

// Initial state
cout << "The light is initially " << (light.getState() == LightState::ON ? "ON" : "OFF")
<< endl;

// Press the switch (event)


light.pressSwitch();

// State after the event


cout << "The light is now " << (light.getState() == LightState::ON ? "ON" : "OFF") <<
endl;

return 0;
}
```

In this example, the event is pressing the light switch, and the states are either the
light being on or off.

15. Different between private and public function.


Ans- The main difference between private and public functions in C++ lies in their
accessibility:
Q & A for C++

### Public Functions:


- **Public functions** are accessible from outside the class.
- They can be accessed by the objects of the class.
- Public functions are used for interfacing with the class.

### Private Functions:


- **Private functions** are only accessible within the class.
- They cannot be accessed by objects of the class.
- Private functions are used for internal class operations and are not accessible
outside the class.

Here is an example to illustrate the difference:

```cpp
#include <iostream>
using namespace std;

class MyClass {
public:
// Public function
void publicFunction() {
cout << "This is a public function" << endl;
privateFunction(); // Can call private functions
}

private:
// Private function
void privateFunction() {
cout << "This is a private function" << endl;
}
};

int main() {
MyClass obj;
obj.publicFunction(); // Can access public function
// obj.privateFunction(); // Cannot access private function
return 0;
}
```

In this example:
- `publicFunction()` is accessible outside the class and can call the private function
`privateFunction()`.
- `privateFunction()` is only accessible within the class and cannot be accessed
outside the class.
16. What do you mean by inline function?
Q & A for C++

Ans- An inline function in C++ is a function that is expanded in place at each point in
the code where it is called. This is in contrast to the normal function call mechanism,
where a function call results in control flow transfer to the function body, and
control returning to the point of call upon completion.

### Characteristics of Inline Functions:


- **Expansion**: The body of the function is copied or expanded at each point
where the function is called.
- **Performance**: Inline functions can provide a performance benefit by reducing
the overhead of a function call.
- **Syntax**: The keyword `inline` is used to declare a function as inline.
- **Small Functions**: Typically, inline functions are small, as expanding larger
functions inline can lead to larger executable code, negating the performance
benefits.

### Example of Inline Function:


```cpp
#include <iostream>
using namespace std;

// Inline function
inline int add(int a, int b) {
return a + b;
}

int main() {
int result = add(5, 3); // Function call is replaced with the function body
cout << "Result: " << result << endl;
return 0;
}
```

In the example above, the `add()` function is declared as an inline function. When
the function is called, the compiler replaces the call with the function body, resulting
in more efficient code execution.
17. What is abstract class?
Ans- An abstract class in C++ is a class that is designed to be specifically used as a
base class. It is a class that cannot be instantiated on its own and is meant to be
subclassed. An abstract class may contain one or more pure virtual functions (also
known as abstract methods) that have no implementation within the base class.
Abstract classes can provide a blueprint for derived classes but cannot be
instantiated themselves.

### Characteristics of an Abstract Class:


- **Cannot be Instantiated**: Objects cannot be created directly from an abstract
class.
Q & A for C++

- **May Contain Concrete Methods**: An abstract class can contain concrete


(implemented) methods along with pure virtual functions.
- **Derived Class Implementation**: The derived class must implement all the pure
virtual functions of the abstract class to become concrete.

### Example of Abstract Class:


```cpp
#include <iostream>
using namespace std;

// Abstract class
class Shape {
public:
// Pure virtual function
virtual void draw() = 0;

// Concrete function
void displayArea() {
cout << "Area: " << calculateArea() << endl;
}

protected:
// Pure virtual function
virtual double calculateArea() = 0;
};

// Derived class Circle


class Circle : public Shape {
private:
double radius;

public:
Circle(double r) : radius(r) {}

// Override the pure virtual function


void draw() {
cout << "Drawing Circle" << endl;
}

protected:
// Override the pure virtual function
double calculateArea() {
return 3.14 * radius * radius;
}
};

// Derived class Rectangle


Q & A for C++

class Rectangle : public Shape {


private:
double length;
double width;

public:
Rectangle(double l, double w) : length(l), width(w) {}

// Override the pure virtual function


void draw() {
cout << "Drawing Rectangle" << endl;
}

protected:
// Override the pure virtual function
double calculateArea() {
return length * width;
}
};

int main() {
// Shape shape; // Error: Cannot instantiate an abstract class

Circle circle(5);
Rectangle rectangle(4, 6);

// Using polymorphism to call the draw function


Shape *shape1 = &circle;
Shape *shape2 = &rectangle;

shape1->draw(); // Output: Drawing Circle


shape1->displayArea(); // Output: Area: 78.5

shape2->draw(); // Output: Drawing Rectangle


shape2->displayArea(); // Output: Area: 24

return 0;
}
```

In this example, `Shape` is an abstract class. Both `Circle` and `Rectangle` are derived
classes that implement the pure virtual function `draw()` and the protected virtual
function `calculateArea()`. Although `Shape` cannot be instantiated, it provides a
blueprint for the derived classes.
18. Define constructor.
Q & A for C++

Ans- C++ is an object oriented programming (OOP) language which provides a special
member function called constructor for initializing an object when it is created. This
is known as automatic initialization of objects.
TYPES OF CONSTRUCTOR-
1- Default constructor
2- Parameterized constructor
3- Copy constructor

To illustrate the use of constructor, let us take the following C++ program:

# include<iostream.h>
# include<conio.h>
class student
{
public:
student() // user defined constructor
{
cout<< “object is initialized”<<end1;
}
};
void main ()
{
student x,y,z;
getch();
}

19. What is control flow statements?


Ans- Control flow statements are a set of programming instructions used to direct
the flow of control within a program's source code. They allow the programmer to
specify the order in which the statements are executed in a program. In C++, the
main control flow statements include:

1. **Conditional Statements:**
- **if**: Executes a block of code if a specified condition is true.
- **else**: Executes a block of code if the same condition is false.
- **else if**: Specifies a new condition to test if the first condition is false.
- **switch**: Evaluates an expression and matches the result to a case clause.

2. **Loops:**
- **for**: Executes a block of code a specified number of times.
- **while**: Executes a block of code as long as a specified condition is true.
- **do...while**: Executes a block of code once, and then repeats the loop as long
as a specified condition is true.

3. **Jump Statements:**
- **break**: Jumps out of a loop or a switch statement.
- **continue**: Skips the rest of the loop and starts the next iteration.
- **return**: Exits the function and returns a value.
Q & A for C++

### Example:
```cpp
#include <iostream>
using namespace std;

int main() {
// Conditional Statements
int x = 10;
if (x > 5) {
cout << "x is greater than 5" << endl;
} else {
cout << "x is not greater than 5" << endl;
}

// Loops
for (int i = 0; i < 5; ++i) {
cout << "Value of i: " << i << endl;
}

// Jump Statements
for (int j = 0; j < 10; ++j) {
if (j == 5) {
break;
}
cout << "Value of j: " << j << endl;
}

return 0;
}
```

In this example:
- A conditional statement checks if `x` is greater than 5.
- A loop prints the value of `i` five times.
- A jump statement breaks out of a loop when `j` equals 5.
20. What is static member function?
Ans- A static member function in C++ belongs to the class rather than any object of
the class. It can be called even if no objects of the class exist and are shared by all
instances of the class. Static member functions have access only to static data
members and other static member functions; they do not have access to `this`
pointer.

### Characteristics of Static Member Functions:


- **Belongs to the Class**: They do not operate on specific instances of the class.
- **Accessed via the class name**: Since they are not associated with any instance
of the class, they are accessed using the class name and the scope resolution
operator `::`.
Q & A for C++

- **Can Access only Static Members**: They can access only static data members
and other static member functions.
- **Can be used for Utility Functions**: They are often used for utility functions that
do not depend on any particular instance of the class.

### Example:
```cpp
#include <iostream>
using namespace std;

class MyClass {
private:
static int count; // Static data member

public:
static void displayCount() { // Static member function
cout << "Count: " << count << endl;
}

void incrementCount() { // Non-static member function


count++;
}
};

int MyClass::count = 0; // Initializing the static data member

int main() {
MyClass::displayCount(); // Calling the static member function

MyClass obj1, obj2;


obj1.incrementCount();
MyClass::displayCount(); // Output: Count: 1

obj2.incrementCount();
MyClass::displayCount(); // Output: Count: 2

return 0;
}
```

In this example:
- `count` is a static data member of the class `MyClass`.
- `displayCount()` is a static member function that can access only static members.
- `incrementCount()` is a non-static member function that increments the static
member `count`.
**Note:** Static member functions can be called using the class name even if no
objects of the class exist.
Q & A for C++

21. What is constraints?


Ans- In the context of databases, a constraint is a rule that is applied to the data
within a database to maintain the integrity, accuracy, and reliability of the data.
Constraints are used to enforce rules at the database level to ensure the quality of
the data.

Here are some common types of constraints:

1. **Primary Key Constraint:**


- Ensures that each record in a database table is uniquely identified.
- Each table can have only one primary key constraint.
- The primary key can consist of one or multiple columns.

2. **Foreign Key Constraint:**


- Enforces referential integrity between two tables.
- It ensures that the values in a particular column in one table match the values in
a column of another table.
- Used to establish a relationship between tables.

3. **Unique Constraint:**
- Ensures that all values in a column or a group of columns are unique.
- Unlike the primary key constraint, a unique constraint allows for null values.

4. **Check Constraint:**
- Verifies that all values in a column satisfy a specific condition.
- The condition can be any logical expression that evaluates to true or false.

5. **Not Null Constraint:**


- Ensures that a column does not accept NULL values.
- It forces a column to have a value.

### Example:
Consider a simple Employee table with the following constraints:

```sql
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID),
CHECK (EmployeeID > 0)
);
```

- **Primary Key Constraint**: `EmployeeID` is the primary key.


- **Unique Constraint**: Both `FirstName` and `LastName` are unique.
Q & A for C++

- **Foreign Key Constraint**: `DepartmentID` references the `Department` table.


- **Check Constraint**: `EmployeeID` must be greater than 0.
- **Not Null Constraint**: Both `FirstName` and `LastName` cannot be NULL.
22. Define object and classes.
Ans- In object-oriented programming:

### Object:
- An object is an instance of a class.
- It is a software bundle of related state and behavior.
- An object can be a variable, a data structure, a function, or a method, and as such,
is a value in memory referenced by an identifier.
- Objects are the basic runtime entities of object-oriented programming.

### Class:
- A class is a blueprint for creating objects (a particular data structure), providing
initial values for state (member variables or attributes), and implementations of
behavior (member functions or methods).
- It is a template or blueprint from which objects are created.
- A class defines the properties and behaviors common to all objects of the same
type.

### Example:
```cpp
#include <iostream>
using namespace std;

// Defining a class
class Car {
public:
// Member variables
string brand;
string model;
int year;

// Member function
void displayInfo() {
cout << "Brand: " << brand << ", Model: " << model << ", Year: " << year << endl;
}
};

int main() {
// Creating objects of the class Car
Car car1, car2;

// Setting properties of car1


car1.brand = "Toyota";
car1.model = "Corolla";
Q & A for C++

car1.year = 2020;

// Setting properties of car2


car2.brand = "Ford";
car2.model = "Mustang";
car2.year = 2019;

// Calling member function to display car information


cout << "Car 1:" << endl;
car1.displayInfo();
cout << "Car 2:" << endl;
car2.displayInfo();

return 0;
}
```

In this example:
- `Car` is a class.
- `car1` and `car2` are objects of the class `Car`.
- `brand`, `model`, and `year` are member variables (or attributes) of the class `Car`.
- `displayInfo()` is a member function (or method) of the class `Car`.
23. Explain about constraints and their use.
Ans- In the context of databases, a constraint is a rule that is applied to the data
within a database to maintain the integrity, accuracy, and reliability of the data.
Constraints are used to enforce rules at the database level to ensure the quality of
the data.
24. What do you mean by concurrency?
25. Explain about object modelling techniques.
26. Explain the concept of structure and class.
27. What do you mean by friend function ?
28. Define constructor .
Ans- C++ is an object oriented programming (OOP) language which provides a special
member function called constructor for initializing an object when it is created. This
is known as automatic initialization of objects.
TYPES OF CONSTRUCTOR-
1- Default constructor
2- Parameterized constructor
3- Copy constructor

To illustrate the use of constructor, let us take the following C++ program:
# include<iostream.h>
# include<conio.h>
class student
{
public:
student() // user defined constructor
{
Q & A for C++

cout<< “object is initialized”<<end1;


}
};
void main ()
{
student x,y,z;
getch();
}
29. Explain unary and binary operators.
30. Differentiate between object and model and function model.
31. Define links and association .
32. State the characteristics of the constructor .
Ans- Characteristics of Constructors
A constructor for a class is needed so that the compiler automatically initializes an object as
soon as it is created. A class constructor if defined is called whenever a program creates an
object of that class. The constructor functions have some special characteristics which are as
follows:
 They should be declared in the public section
 They are invoked directly when an object is created.
 They don’t have return type, not even void and hence can’t return any values.
 They can’t be inherited; through a derived class, can call the base class
 constructor. Like other C++ functions, they can have default arguments.
 Constructors can’t be virtual.
 Constructor can be inside the class definition or outside the class definition.
 Constructor can’t be friend function.
 They can’t be used in union.
 They make implicit calls to the operators new and delete when memory
 allocation is required.
33. What is meta data?
34. What is tokens?
35. Explain what is mint by a method.
36. Define state and events.
37. What is the role of ‘this’ pointer?
38. Differentiate between class and structure.
39. Why it is necessary to overload an operator?
40. What is an abstract class?
41. What are basic symbols used for drawing DFD ?

Ans- Certainly! Data Flow Diagrams (DFDs) use standard symbols to represent
various components. Let’s take a look at the primary symbols used in DFDs:

1. External Entity (Entity): Represented by squares or rectangles, external


entities are sources or destinations of data. They produce and consume data
that flows between the entity and the system being diagrammed. These
entities can be other systems, subsystems, or external actors interacting with
the system1.
Q & A for C++

2. Process: Processes are represented by rectangles with rounded corners.


They denote activities that change or transform data flows within the
system. Processes have inputs and outputs, as they transform incoming data
into outgoing data1.

3. Data Flow (Arrow): Arrows indicate the physical or electronic flow of


data. They represent how data moves from one component to another. Data
flows connect external entities, processes, and data stores within the DFD1.

4. Data Store: Data stores are physical or electronic storage points. They are
represented by open-ended rectangles. Data stores can be files, databases, or
other storage mechanisms where data is stored within the system2.

Remember that consistency in notation is essential to avoid confusion. Whether


you’re using Yourdon-Coad or Gane-Sarson notation, make sure to follow the
same set of symbols throughout your DFD1. If you’re using DFD software, it will
likely dictate which symbols are available for use.

42. What are the protected member of a class?


43. What do you mean by prototyping?
44. What is role of a destructor?
Ans- The destructor in C++ is a special member function that is automatically called
when an object goes out of scope or is explicitly deleted. Its primary role is to clean
up resources allocated by the object during its lifetime, such as dynamic memory
allocation, file handles, network connections, or any other resources acquired during
object initialization.
45. What is the role of virtual base class ?
46. Explain the relation between an object and class.
47. what is the purpose of a storage class ?
48. what is OMT class ?

Ans- Certainly! Here’s a concise answer:

OMT (Object Modeling Technique) is a modeling approach used for software


design. It focuses on the static structure of a system and describes its components.
Key concepts in OMT include:

1. Object Model:
o Represents classes (abstract or concrete) using rectangles.
Q & A for C++

o Abstract classes are shown in italic font, while concrete classes use
roman font.
o Interfaces represent types, and concrete classes are named
implementations of interfaces.
2. Dynamic Model:
o Deals with states, events, and state diagrams.
o Includes transitions between states triggered by events.
3. Functional Model:
o Describes data flow, storage, and processes.
o Uses data flow diagrams (DFD) to depict system processes.

OMT helps in developing object-oriented systems and solving real-world


problems.

1. Discuss the concept of Evens And States with suitabale example.

Ans- Certainly! Let’s delve into the concepts of states, events, and transitions in
the context of system modeling:

1. States:
o A state represents the current condition of a system at a specific point
in time. It captures all relevant data and variables that define the
system’s state.
o For instance, consider a video game. The game’s state includes the
player’s position, obstacle locations, the score, and other relevant
information.
o In modeling, states represent different phases or conditions of a
system. They can be simple (e.g., “on” and “off”) or complex,
depending on the system’s complexity1.
2. Events:
o An event is an occurrence that triggers a change in the system’s state.
Events can be internal or external to the system.
o Examples of events include a user pressing a button, a timer expiring,
or environmental factors affecting the system.
o Events model the behavior of a system over time by defining actions
that cause state transitions1.
3. Transitions:
o Transitions occur when an event leads to a change in the system’s
state.
o For instance, when a traffic light transitions from “red” to “green,” it
changes its state based on an event (e.g., a timer).
o Transitions are essential for understanding how a system behaves as it
moves between different states1.

Example: Traffic Light System


Q & A for C++

 Let’s use a simple example of a traffic light:


o States: The traffic light has three states: “red,” “yellow,” and “green.”
o Events:
 “Timer”: The timer event triggers transitions between states.
 “Button Press”: If a pedestrian presses a button, it can cause a
transition (e.g., from “red” to “green”).
o Transitions:
 When the timer expires, the traffic light transitions from “red”
to “green.”
 If a button is pressed, the traffic light transitions from any state
to “green” to allow pedestrians to cross1.

Remember, these concepts help model various systems, from software applications
to physical devices. They provide a foundation for understanding how systems
evolve over time. 1

You might also like