Which statement is true about pure virtual functions in C++?a)A pure v...
A class containing a pure virtual function is called an abstract class. An abstract class cannot be instantiated, meaning objects of the abstract class cannot be created. However, a derived class can inherit from the abstract class and provide implementations for the pure virtual functions.
View all questions of this test
Which statement is true about pure virtual functions in C++?a)A pure v...
Explanation:
A pure virtual function is a function in a base class that has no implementation and is meant to be overridden by derived classes. It is declared using the syntax `virtual returnType functionName(parameters) = 0;`.
Statement: A class containing a pure virtual function cannot be instantiated.
Explanation:
This statement is true. A class that contains a pure virtual function is called an abstract class. An abstract class cannot be instantiated, which means that objects of the abstract class cannot be created. The reason behind this is that the pure virtual function does not have an implementation in the base class, so it cannot be called.
When a class contains a pure virtual function, it becomes an abstract class. The purpose of an abstract class is to provide a common interface for all its derived classes. Each derived class must implement the pure virtual function, providing its own implementation. By making the base class abstract, we ensure that the derived classes must override the pure virtual function.
An example of an abstract class in C++:
```
class Shape {
public:
virtual void draw() = 0; // pure virtual function
};
class Circle : public Shape {
public:
void draw() {
// implementation of draw for Circle
}
};
class Rectangle : public Shape {
public:
void draw() {
// implementation of draw for Rectangle
}
};
```
In this example, the `Shape` class is an abstract class because it contains a pure virtual function `draw()`. The `Circle` and `Rectangle` classes are derived from `Shape` and provide their own implementation of the `draw()` function.
Attempting to create an object of the `Shape` class directly will result in a compilation error because the `Shape` class is abstract and cannot be instantiated:
```
Shape shape; // Error: cannot instantiate abstract class
```
Instead, we can create objects of the derived classes:
```
Circle circle;
Rectangle rectangle;
```
In conclusion, a class containing a pure virtual function cannot be instantiated, making the statement true.