Unit 3
Unit 3
Placements
Welcome to Turning Point by Ankush Saklecha, your one-stop destination for GATE CSE
preparation, semester exams, and placement guidance. Stay connected with us across various
platforms for expert mentorship, study materials, and career guidance.
�Get everything you need to excel in academics and secure top placements!
�Join our Telegram Group for interactive discussions and quick solutions to your doubts.
�Follow us on Instagram, LinkedIn, and YouTube for exclusive content and live updates.
�Prepare for GATE, semester exams, and placements with the best resources. Stay connected,
stay ahead!
Unit 3
Questions:
Q1.
What is constructor and destructor function? Explain with an
example.
Q2.
Explain the various types of constructor with a programming
example.
Q3.
Describe the role of Inheritance in object-oriented programming.
Give different types of inheritance.
Q4.
What is Inheritance? What are the different forms of
Inheritance? Write suitable codes to illustrate them.
Q5.
What is Constructor? Is it mandatory to use Constructor in a
class?
Q6.
What is meant by Abstract class?
Q7.
Compare aggregation and inheritance. Write down the properties
of aggregation.
Q8.
What is an abstract class in OOP and how do we implement it?
Explain with an example.
Q9.
Explain the concept of interfaces and abstract class in detail.
Q1.
What is constructor and destructor function? Explain with an
example.
Constructor
Characteristics of a Constructor:
Destructor
A destructor is a special function that gets automatically called when an
object goes out of scope or is deleted. It is used to release resources
(e.g., memory allocation, file handling).
Characteristics of a Destructor:
Example 1:
#include <iostream>
using namespace std;
class Demo {
public:
Demo() {
cout << "Constructor called! Object is created." << endl;
}
~Demo() {
cout << "Destructor called! Object is destroyed." << endl;
}
};
int main() {
Demo obj; // Constructor is called when the object is created
cout << "Inside main function." << endl;
return 0; // Destructor is called automatically when the object
goes out of scope
}
Example 2:
#include <iostream>
using namespace std;
class Student {
private:
string name;
int age;
public:
// Parameterized Constructor
Student(string n, int a) {
name = n;
age = a;
cout << "Constructor called! Student object created." << endl;
}
// Function to display student details
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
// Destructor
~Student() {
cout << "Destructor called! Student object destroyed." <<
endl;
}
};
int main() {
Student s1("Alice", 20); // Constructor is called
s1.display();
{
// Creating another object inside a block
Student s2("Bob", 22);
s2.display();
} // s2 goes out of scope here, so its destructor is called
Q2.
What is Constructor? Is it mandatory to use Constructor in a
class?
Constructors
Constructors are special class members which are called by the
compiler every time an object of that class is instantiated.
Constructors have the same name as the class and may be
defined inside or outside the class definition.
There are 3 types of constructors:
1. Default Constructors
2. Parameterized Constructors
3. Copy Constructors
Characteristics of a Constructor:
class Test {
public:
int x; // Not explicitly initialized
};
int main() {
Test obj; // Compiler provides a default constructor
cout << "Value of x: " << obj.x << endl;
return 0;
}
#include <iostream>
using namespace std;
Example With Constructor
class Test {
public:
int x;
// Constructor
Test() {
x = 10; // Explicit initialization
cout << "Constructor called!" << endl;
}
};
int main() {
Test obj; // Calls constructor automatically
cout << "Value of x: " << obj.x << endl;
return 0;
}
#include <iostream>
using namespace std;
class Student {
private:
string name;
int age;
public:
// 1. Default Constructor
Student() {
name = "Unknown";
age = 0;
cout << "Default Constructor Called!" << endl;
}
// 2. Parameterized Constructor
Student(string n, int a) {
name = n;
age = a;
cout << "Parameterized Constructor Called!" << endl;
}
// 3. Copy Constructor
Student(const Student &s) {
name = s.name;
age = s.age;
cout << "Copy Constructor Called!" << endl;
}
int main() {
// Default Constructor
Student s1;
s1.display();
// Parameterized Constructor
Student s2("Alice", 20);
s2.display();
// Copy Constructor
Student s3 = s2; // Copying s2 into s3
s3.display();
return 0;
}
Q3.
Describe the role of Inheritance in object-oriented programming.
Give different types of inheritance.
Types of Inheritance
1. Single Inheritance
Example:
#include <iostream>
using namespace std;
class Animal {
public:
void eat() { cout << "Eating...\n"; }
};
int main() {
Dog d;
d.eat(); // Inherited from Animal
d.bark(); // Own method
return 0;
}
2. Multiple Inheritance
class Engine {
public:
void startEngine() { cout << "Engine started\n"; }
};
class Wheels {
public:
void rotateWheels() { cout << "Wheels rotating\n"; }
};
int main() {
Car myCar;
myCar.startEngine();
myCar.rotateWheels();
myCar.drive();
return 0;
}
Ambiguity in Multiple inheritance: If two parent classes have
the same method name, ambiguity arises. This can be solved using
scope resolution (ParentClass::methodName())
3. Multilevel Inheritance
#include <iostream>
using namespace std;
class Animal {
public:
void breathe() { cout << "Breathing...\n"; }
};
#include <iostream>
using namespace std;
class Parent {
public:
void show() { cout << "This is the Parent class\n"; }
};
int main() {
Child1 c1;
Child2 c2;
c1.show(); // Inherited
c1.display1();
c2.show(); // Inherited
c2.display2();
return 0;
}
Real-World Example
Parent Class:BankAccount
Child Classes:SavingsAccount, CheckingAccount, LoanAccount
Each child class has unique functionalities but shares common
properties from BankAccount.
#include <iostream>
using namespace std;
class A {
public:
void show() { cout << "Class A\n"; }
};
class B : public A { };
class C : public A { };
int main() {
D obj;
// obj.show(); // ERROR: Ambiguity - which A::show() to call?
return 0;
}
1. Solution: Virtual Inheritance
To prevent duplication, we use virtual in the base classes.
#include <iostream>
using namespace std;
class A {
public:
void show() { cout << "Class A\n"; }
};
int main() {
D obj;
obj.show(); // Now, there's only one copy of A::show()
return 0;
}
// Base class A
class A {
public:
void func() {
cout << " I am in class A" << endl;
}
};
// Base class B
class B {
public:
void func() {
cout << " I am in class B" << endl;
}
};
// Derived class C
class C: public A, public B {
};
// Driver Code
int main() {
return 0;
}
Inheritance
Description Example
Type
One child class inherits from one
Single Car inherits from Vehicle
parent class
One child class inherits from All-in-One Printer from
Multiple
multiple parent classes Printer&Scanner
Chain of inheritance (child -> Parrot inherits from Bird, Bird
Multilevel
parent -> grandparent) from LivingBeing
SavingsAccount,
Multiple child classes inherit
Hierarchical CheckingAccount from
from a single parent class
BankAccount
Combination of two or more
Intern inherits from Student and
Hybrid types, can cause diamond
Employee
problem
Q4.
Compare aggregation and inheritance. Write down the properties
of aggregation.
A relationship A relationship
where one class where one class
Definition contains an object of derives properties
another class (HAS- and behavior from
A relationship). another (IS-A
Feature Aggregation Inheritance
relationship).
#include <iostream>
using namespace std;
class Engine {
public:
void start() { cout << "Engine started\n"; }
};
class Car {
private:
Engine engine; // Aggregation: Car HAS-A Engine
public:
void startCar() {
engine.start(); // Using Engine's method
cout << "Car is running\n";
}
};
int main() {
Car myCar;
myCar.startCar();
return 0;
}
Properties of Aggregation
1. HAS-A Relationship: Aggregation represents a whole-part
relationship, where one class contains another as an object.
2. Weak Association: The contained object can exist independently
of the container class.
3. No Inheritance: Aggregation does not use extends (like
inheritance) but instead uses object references.
4. Better Maintainability: Changes in one class do not heavily
impact the other.
5. Reusability: The same component (object) can be shared across
multiple classes.
6. Composition vs. Aggregation: Aggregation allows independent
lifetimes, whereas composition implies the contained object
cannot exist without the container.
7. Memory Efficiency: Reduces memory overhead compared to
inheritance, as only required objects are stored.
Q5.
What is an abstract class in OOP and how do we implement it?
Explain with an example.
#include <iostream>
using namespace std;
// Abstract class
class Animal {
public:
virtual void makeSound() = 0; // Pure virtual function (abstract
method)
void sleep() {
cout << "Sleeping...\n";
}
};
// Derived class
class Dog : public Animal {
public:
void makeSound() override { // Implementation of abstract
method
cout << "Dog barks: Woof Woof!\n";
}
};
int main() {
// Animal a; // ERROR: Cannot instantiate an abstract class
Dog d;
d.makeSound(); // Calls overridden method
d.sleep(); // Calls inherited concrete method
return 0;
}
Explanation:
Q 6.
Explain the concept of interfaces and abstract class in detail.
interface Animal {
void makeSound(); // Abstract method (implicitly public &
abstract)
}
Can have both abstract and Only abstract methods (Java 8 allows
Methods
concrete methods default and static methods)
Variables Can have instance variables Only public static final (constants)
Used for base classes with shared Used for defining behavior contracts
Use Case
behavior without implementation
Feature Abstract Class Interface
// Abstract Class
abstract class Animal {
abstract void makeSound();
void sleep() {
System.out.println("Sleeping...");
}
}
// Interface
interface Pet {
void play();
}
Definition:
Generalization is the process of extracting common features from two or more
classes and creating a generalized superclass.
It follows a bottom-up approach, where multiple specific classes share
common attributes and methods, which are moved to a higher-level superclass.
It represents an "IS-A" relationship.
Example:
Car and Truck share common properties, so they are generalized into a
superclass Vehicle.
// Generalized superclass
class Vehicle {
String brand;
void start() {
System.out.println("Vehicle is starting...");
}
}
// Specialized subclasses
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving...");
}
}
class Truck extends Vehicle {
void loadCargo() {
System.out.println("Truck is loading cargo...");
}
}
Example:
// General class
class Employee {
String name;
double salary;
void work() {
System.out.println(name + " is working...");
}
}
// Specialized subclasses
class Developer extends Employee {
void code() {
System.out.println(name + " is writing code.");
}
}
Creating specialized
Extracting common features to create a
Definition subclasses by adding unique
generalized superclass.
features.
Parent class is created from multiple Child classes are derived from
Relationship
child classes. a parent class.
by moving common
Avoid redundancy Add new specific behaviors to
Purpose
properties/methods to a superclass. subclasses.