Inheritance
Published by
sanya sanya
Introduction
The process by which a new class (derived class) is created from an existing class (base class). The derived class inherits the properties and behaviors of the base class and can extend or modify them as needed. It facilitates code reuse and creates a hierarchical relationship between classes.
Inheriting classes and subclasses
Classes can be inherited to create subclasses (also known as derived classes). The subclass inherits the properties and behaviors (data members and member functions) of the base class (also known as the parent class). This relationship is established using the colon (‘:’) symbol followed by the access specifier (‘public’, ‘protected’, or ‘private’) and the name of the base class during the subclass declaration.
Syntax:
class BaseClass {
// Base class members
};
class SubClass : access-specifier BaseClass {
// Subclass members
};
Access-specifier specifies how the members of the base class are accessible in the derived class:
- 'public': All of the base class's public members are also public members of the derived class.
- ‘protected’: All of the base class's public members are now protected members of the derived class.
- ‘private’: All of the base class's public members are converted to private members of the derived class.
Example:
#include
#include
using namespace std;
// Base class
class Animal {
public:
string name;
void makeSound() {
cout << "Animal makes a sound" << endl;
}
};
// Derived class inheriting from Animal
class Dog : public Animal {
public:
void makeSound() {
cout << "Dog barks" << endl;
}
void fetch() {
cout << "Dog fetches a ball" << endl;
}
};
int main() {
Dog myDog;
myDog.name = "Buddy";
myDog.makeSound(); // Output: Dog barks
myDog.fetch(); // Output: Dog fetches a ball
return 0;
}
In this example, we have a base class ‘Animal’ with a member variable ‘name’ and a member function ‘makeSound()’. The derived class ‘Dog’ inherits from ‘Animal’ using the ‘public’ access specifier. The ‘Dog’ class also defines its own member function ‘fetch()’.
When we create an object ‘myDog’ of the ‘Dog’ class, it inherits the ‘name’ member from the ‘Animal’ class and can call the ‘makeSound()’ function from both the ‘Animal’ and ‘Dog’ classes. The ‘fetch()’ function is specific to the ‘Dog’ class and can only be called for ‘myDog’.
Library
WEB DEVELOPMENT
FAANG QUESTIONS