Oop Answebook
Oop Answebook
Oop Answebook
1. Types of Constructor
Constructors are special member functions used to initialize objects of a class. There are
three main types:
a) Default Constructor
A default constructor is a constructor with no parameters, used to initialize default values.
Example:
class MyClass:
def __init__(self):
self.value = 0
obj = MyClass()
print(obj.value) # Output: 0
b) Parameterized Constructor
A parameterized constructor accepts arguments to initialize class members with specific
values.
Example:
class MyClass:
def __init__(self, value):
self.value = value
obj = MyClass(10)
print(obj.value) # Output: 10
c) Copy Constructor
A copy constructor initializes an object using another object of the same class.
Example:
class MyClass:
def __init__(self, value):
self.value = value
def copy_constructor(self, obj):
self.value = obj.value
obj1 = MyClass(10)
obj2 = MyClass(0)
obj2.copy_constructor(obj1)
print(obj2.value) # Output: 10
2. Inheritance
Inheritance allows a class (derived class) to acquire properties and methods of another
class (base class).
Types of inheritance:
1. Single Inheritance
2. Multi-level Inheritance
a) Single Inheritance
Example:
class Parent:
def display(self):
print("This is the parent class.")
class Child(Parent):
pass
obj = Child()
obj.display()
b) Multi-level Inheritance
Example:
class Grandparent:
def display_grandparent(self):
print("This is the grandparent class.")
class Parent(Grandparent):
def display_parent(self):
print("This is the parent class.")
class Child(Parent):
pass
obj = Child()
obj.display_grandparent()
obj.display_parent()
3. Polymorphism
Polymorphism allows methods in different classes to have the same name but behave
differently.
Types:
1. Compile-time Polymorphism (Method Overloading)
2. Runtime Polymorphism (Method Overriding)
4. Operator Overloading
Example of Overloading a Binary Operator (+):
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
c1 = Complex(1, 2)
c2 = Complex(3, 4)
c3 = c1 + c2
print(f"Result: {c3.real} + {c3.imag}i")
5. Virtual Function
Virtual functions are member functions in the base class that can be overridden in derived
classes.
The call to a virtual function is resolved at runtime.
Example:
class Base:
def display(self):
print("Base class")
class Derived(Base):
def display(self):
print("Derived class")
obj = Derived()
obj.display() # Output: Derived class
6. Function Overloading
Function overloading allows multiple functions with the same name but different
parameters.
obj = MyClass()
obj.display() # Output: No value provided
obj.display(10) # Output: Value: 10