C++ Deriving Classes from Existing Classes
In C++, you can create a new class by deriving it from an existing class. This is known as inheritance, where the new class, called the derived class or subclass, inherits the properties of the existing class, called the base class or superclass.
The syntax for deriving a new class from an existing class in C++ is as follows:
class DerivedClass : [access-specifier] BaseClass { // members and functions };
Here, DerivedClass
is the name of the new class you want to create, and BaseClass
is the name of the existing class you want to derive from. The access-specifier
is optional and specifies the access level for the derived class. The access specifiers are public
, protected
, and private
, and they control the visibility of the inherited members in the derived class. If no access specifier is specified, the default access level is private.
When you derive a class from a base class, the derived class inherits all the data members and member functions of the base class, except for its constructors and destructors. The constructors and destructors of the base class can be called from the derived class using special syntax, as shown below:
class BaseClass { public: BaseClass(int x) { // constructor code } ~BaseClass() { // destructor code } }; class DerivedClass : public BaseClass { public: DerivedClass(int x, int y) : BaseClass(x) { // constructor code } ~DerivedClass() { // destructor code } };
In this example, the derived class DerivedClass
calls the constructor of the base class BaseClass
with the argument x
using the syntax BaseClass(x)
. The destructor of the base class is automatically called when the derived class object is destroyed.
When you override a member function in the derived class, you use the virtual
keyword in the base class declaration and the override
keyword in the derived class declaration. This is necessary to ensure that the derived class member function overrides the base class member function correctly. Here's an example:
class BaseClass { public: virtual void foo() { std::cout << "BaseClass::foo()\n"; } }; class DerivedClass : public BaseClass { public: void foo() override { std::cout << "DerivedClass::foo()\n"; } };
In this example, the foo()
function in the base class BaseClass
is declared virtual
, and the derived class DerivedClass
overrides it using the override
keyword. When you call the foo()
function on an object of the derived class, it calls the derived class version of the function.
In summary, deriving a class from an existing class in C++ allows you to reuse code and functionality from the base class in the derived class. You can call the constructors and destructors of the base class, override the base class member functions, and use the inherited data members and member functions in the derived class.