Multilevel Inheritence

08 Dec 2019

Comparision between constructor call order in CPP and initializer call order in Python while Inheritance

Introduction

CPP

#include<iostream> 
using namespace std; 

class A 
{ 
public: 
A() { cout << "A's constructor called" << endl; } 
}; 

class B: public A
{ 
public: 
B() { cout << "B's constructor called" << endl; } 
}; 

class C: public B // Note the order 
{ 
public: 
C() { cout << "C's constructor called" << endl; } 
}; 

int main() 
{ 
	C c; 
	return 0; 
} 

Output:

A's constructor called
B's constructor called
C's constructor called

Python

# Program to define the use of super() 
# function in multiple inheritance 
class A: 
	def __init__(self): 
		print('A's initializer called.') 

	def foo(self, b): 
		print('Printing from class A:', b) 

class B(A): 
	def __init__(self): 
		print('B's initializer called.') 

	def foo(self, b): 
		print('Printing from class B:', b) 

class C(B):
	def __init__(self): 
		print('C's initializer called.') 

	def foo(self, b): 
		print('Printing from class C:', b) 

# main function 
if __name__ == '__main__': 
	obj = C() 

Output:

C's initializer called.

super

Polymorphism

License

MIT