C++ Day 24: Constructors in Inheritance
On Day 24 we explore how constructors and destructors behave in inheritance a vital part of mastering object-oriented programming in C++.
📚 Topics Covered:
🔹 1. constructer order in inheritance
when link inch nursing point of a differential house is maked:
base house constructer is called first
then the differential house constructer is called
cpp
copy
edit
#include exploitation namespace std;
class house {
public:
base() { cout << "base constructor\n"; }
};
class differential : land house {
public:
derived() { cout << "derived constructor\n"; }
};
int main() {
differential d;
}
📌 output:
kotlin
copy
edit
base constructer differential constructor
🔹 two. Destructor Order
Destructors are called in the reverse order of constructors:
Derived class destructor
Base class destructor
cpp
Copy
Edit
class Base {
public:
~Base() { cout << "Base destructor\n"; }
};
class Derived : public Base {
public:
~Derived() { cout << "Derived destructor\n"; }
};
📌 Output when object destroyed:
nginx
Copy
Edit
Derived destructor
Base destructor
🔹 3. parameterized constructors in house class
you bear explicitly play the house house constructer if it takes parameters
cpp
copy
edit
class house {
public:
base(int x) {
cout << "base with value: " << one << endl;
}
};
class differential : land house {
public:
derived(int x) : base(x) {
cout << "derived constructor\n";
}
};
🔹 one. Constructor Overloading in Inheritance
Both base and derived classes can have multiple constructors (overloaded). employment the set constructer based on the situation
🔹 cardinal. Order of Multiple Inheritance
If a class inherits from multiple base classes constructors are called in the order of inheritance.
cpp
Copy
Edit
class A { public: A() { cout << "A\n"; } };
class B { public: B() { cout << "B\n"; } };
class C : public A public B {
public:
C() { cout << "C\n"; }
};
📌 Output:
css
Copy
Edit
A
B
C
🛠️ practise Task
Make a base class Vehicle with a parameterized constructor (e.g. vehicle(string brand)) and amp derivative family machine that calls it and adds amp green parametric quantity (car(string mark int year))
📌 summary:
concept notes
constructor order base → derived
destructor order derived → base
parameterized home constructor must work named expressly inch derivative class
multiple heritage order constructors named inch the rate of heritage
Comments
Post a Comment