Untitled
unknown
plain_text
a year ago
1.3 kB
5
Indexable
**Virtual Keyword:**
In C++, the `virtual` keyword is used to declare a function that can be overridden by a derived class. A virtual function is a member function of a class that can be redefined by a derived class.
**Virtual Constructor:**
There is no such thing as a virtual constructor in C++. Constructors are special member functions that are used to initialize objects when they are created, and they cannot be declared as virtual.
**Virtual Destructor:**
A virtual destructor is a destructor that is declared as virtual in a base class. This allows the correct destructor to be called when an object of a derived class is deleted through a pointer to the base class.
Example:
```c
class Base {
public:
virtual ~Base() {} // virtual destructor
};
class Derived : public Base {
public:
~Derived() {} // destructor
};
int main() {
Base* p = new Derived();
delete p; // calls Derived's destructor and then Base's destructor
return 0;
}
```
In this example, if the `Base` class did not have a virtual destructor, the `Derived` class's destructor would not be called when `p` is deleted, leading to undefined behavior. By declaring the `Base` class's destructor as virtual, we ensure that the correct destructor is called for the `Derived` class.Editor is loading...
Leave a Comment