Classes Inheritance
Inheritance allows a new class (derived class) to inherit properties and behavior from an existing class (base class).
class BaseClass {
public:
int baseNumber;
};
class DerivedClass : public BaseClass {
public:
int derivedNumber;
};
Constructor and Destructor
In inheritance the order of constructor call is Base
-> Derived
and the revers in Destructor Derived
-> Base
#include
using namespace std;
// Base class
class Base {
public:
Base(){
cout << "Base class default constructor!" << endl;
}
~Base(){
cout << endl << "Base class Destructor!" ;
}
};
// Derived class
class Derived : public Base {
public:
Derived(){
cout << "Derived class default constructor!" << endl;
}
~Derived(){
cout << endl << "Derived class Destructor!" ;
}
};
// main function
int main() {
// creating object of Derived Class
Derived obj;
}
The output will be
Base class default constructor!
Derived class default constructor!
Derived class Destructor!
Base class Destructor!
Function Overriding
When a derived class inherits from a base class, it may choose to change some of the inherited functionality.
This consider a Run-time Polymorphism
#include
// Base class
class Animal {
public:
// Virtual function to be overridden
virtual void sound() {
std::cout << "Animal makes a sound!" << std::endl;
}
};
// Derived class
class Dog : public Animal {
public:
// Override the base class method
void sound() override {
std::cout << "Dog barks!" << std::endl;
}
};
To override a method, the signature of the overridden method of the base class has to match exactly.
virtual
You use the virtual
keyword when you want to allow derived classes to override a base class function to provide their own implementation, while ensuring that the correct function is called at runtime based on the actual object type, not the type of the pointer or reference.
class Base {
public:
virtual void speak() { std::cout << "Base speaking\n"; }
};
class Derived : public Base {
public:
void speak() override { std::cout << "Derived speaking\n"; }
};
Base* obj = new Derived();
obj->speak(); // Calls Derived's speak() due to virtual function
overriding a virtual
function in a derived class is optional. If the derived class doesn't override the virtual function, the base class's version of the function will be used when the function is called.
class Base {
public:
virtual void speak() = 0; // Pure virtual function
};
class Derived : public Base {
public:
void speak() override { std::cout << "Derived speaking\n"; } // Must override
};
In this case,
Derived
must overridespeak()
; otherwise, it will be abstract and cannot be instantiated.
final
final
supports two use cases.
- we can declare a method that cannot be overridden.
- we can define a class that cannot be derived from
We can not use
virtual
andfinal
together on the same function.