0% found this document useful (0 votes)
2 views

Unit 3

Turning Point by Ankush Saklecha is a comprehensive resource for GATE CSE preparation, semester exams, and placement guidance, offering high-quality content, mock tests, and mentorship. The platform includes an app, a Telegram community for discussions, and social media channels for updates and career tips. It covers key programming concepts such as constructors, destructors, inheritance, and aggregation in object-oriented programming with examples and explanations.

Uploaded by

2810aryansh0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit 3

Turning Point by Ankush Saklecha is a comprehensive resource for GATE CSE preparation, semester exams, and placement guidance, offering high-quality content, mock tests, and mentorship. The platform includes an app, a Telegram community for discussions, and social media channels for updates and career tips. It covers key programming concepts such as constructors, destructors, inheritance, and aggregation in object-oriented programming with examples and explanations.

Uploaded by

2810aryansh0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Turning Point – Your Ultimate Guide for GATE CSE, Semester Exams &

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.

� GATE CSE | Semester Exams | Placement Preparation


 GATE CSE – High-quality content, previous year questions, mock tests & expert strategies.
 Semester Exams – Conceptual clarity, important topics, and subject-wise revision.
 Placement Preparation – Coding practice, aptitude, technical & HR interview guidance.

�Get everything you need to excel in academics and secure top placements!

� Download the Turning Point App


Access GATE CSE, semester, and placement preparation resources in one place.
�Download Now: Turning Point App

� Join Our Telegram Community


�Telegram Group: Join Now (Discuss doubts, strategies & placement tips)
�Telegram Channel: Follow Updates (Get study materials, exam notifications & job updates)

�Join our Telegram Group for interactive discussions and quick solutions to your doubts.

� Connect with Us on Social Media


Stay updated with study materials, placement preparation tips, and special announcements
by following us:

�Facebook: Turning Point with Ankush Saklecha


�Instagram: Follow Us (Daily motivation, study hacks & live sessions)
�LinkedIn: Connect with Ankush Saklecha (Professional updates & industry insights)

�Follow us on Instagram, LinkedIn, and YouTube for exclusive content and live updates.

� Stay Updated & Get Placed!


✔ Join our Telegram Group for GATE CSE & Placement discussions.
✔ Follow us on Instagram & LinkedIn for career tips & updates.
✔ Subscribe to our YouTube Channel for coding & interview guidance.
✔ Download the Turning Point App for structured learning & career growth.

�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.

In C++, constructors and destructors are special member functions of


a class that are used for initializing and cleaning up objects, respectively.

Constructor

A constructor is a special function that gets automatically called when an


object of a class is created. It is used to initialize object properties.

Characteristics of a Constructor:

 Has the same name as the class.


 Does not have a return type (not even void).
 Can be overloaded (multiple constructors in the same class).
 Can have default, parameterized, and copy constructors.

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:

 Has the same name as the class but prefixed with a ~.


 Does not take any arguments.
 Cannot be overloaded.
 Does not return any value.

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

cout << "Back to main function." << endl;


return 0; // s1 goes out of scope, 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:

 Has the same name as the class.


 Does not have a return type (not even void).
 Can be default (no parameters), parameterized, or copy
constructor.
 Can be overloaded (multiple constructors in a class).
 Gets invoked automatically when an object is created.
Is it Mandatory to Use a Constructor in a Class?
No, it is not mandatory to define a constructor in a class.

If a constructor is not explicitly defined, the compiler


automatically provides a default constructor that initializes
objects with default values.
However, if an object needs custom initialization, a constructor
is necessary.
Example Without Constructor
#include <iostream>
using namespace std;

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;
}

1. Default Constructor (No parameters, initializes default values)

2. Parameterized Constructor (Takes arguments for initialization)


3. Copy Constructor (Creates a new object as a copy of an existing
object)
Example:

#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;
}

// Function to display student details


void display() {
cout << "Name: " << name << ", Age: " << age << 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.

 The "IS-A" relationship represents inheritance in Object-Oriented


Programming (OOP). It is used when a class inherits properties
and behavior from another class.
If a class B extends class A, we say BIS-AA
 Inheritance is a fundamental concept in OOP that allows one class
(the child/subclass) to inherit properties and behaviors (fields and
methods) from another class (the parent/superclass). The primary
purposes of inheritance are:

1. Code Reusability – Avoids duplication by allowing derived


classes to reuse code from the base class.
2. Modularity & Maintainability – Enhances the organization of
code and simplifies updates.
3. Extensibility – Allows for the extension of existing functionality
without modifying the original class.
4. Polymorphism – Enables objects of derived classes to be treated
as objects of the base class, improving flexibility.
5. Abstraction – Helps in creating a general class structure, allowing
specialization in derived classes.

Types of Inheritance

Inheritance can be categorized into the following types:

1. Single Inheritance

Single inheritance occurs when a subclass (child class) inherits from a


single superclass (parent class). The child class gets access to the
properties and behaviors of the parent class.

Example:
#include <iostream>
using namespace std;

class Animal {
public:
void eat() { cout << "Eating...\n"; }
};

class Dog : public Animal {


public:
void bark() { cout << "Barking...\n"; }
};

int main() {
Dog d;
d.eat(); // Inherited from Animal
d.bark(); // Own method
return 0;
}

2. Multiple Inheritance

A subclass inherits from more than one superclass, gaining


attributes and behaviors from multiple sources.
#include <iostream>
using namespace std;

class Engine {
public:
void startEngine() { cout << "Engine started\n"; }
};

class Wheels {
public:
void rotateWheels() { cout << "Wheels rotating\n"; }
};

class Car : public Engine, public Wheels {


public:
void drive() { cout << "Car is moving\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

A class is derived from another derived class, forming a hierarchy.

#include <iostream>
using namespace std;

class Animal {
public:
void breathe() { cout << "Breathing...\n"; }
};

class Mammal : public Animal {


public:
void walk() { cout << "Walking...\n"; }
};

class Human : public Mammal {


public:
void speak() { cout << "Speaking...\n"; }
};
int main() {
Human h;
h.breathe(); // Inherited from Animal
h.walk(); // Inherited from Mammal
h.speak(); // Own method
return 0;}
4. Hierarchical Inheritance

A single parent class is inherited by multiple child classes.

#include <iostream>
using namespace std;

class Parent {
public:
void show() { cout << "This is the Parent class\n"; }
};

class Child1 : public Parent {


public:
void display1() { cout << "Child 1 class\n"; }
};

class Child2 : public Parent {


public:
void display2() { cout << "Child 2 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.

5. Hybrid Inheritance (Virtual Inheritance)


A combination of two or more types of inheritance. This often
leads to the diamond problem, where a class inherits from two
classes that share a common base class.
The Diamond Problem
When a class inherits from two classes that both inherit from the
same base class, it gets two copies of the base class, causing
ambiguity.

#include <iostream>
using namespace std;

class A {
public:
void show() { cout << "Class A\n"; }
};

class B : public A { };
class C : public A { };

class D : public B, public C { };

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"; }
};

class B : virtual public A { };


class C : virtual public A { };

class D : public B, public C { };

int main() {
D obj;
obj.show(); // Now, there's only one copy of A::show()
return 0;
}

2. Solution: To solve this ambiguity scope resolution operator is


used denoted by ‘ :: ‘
#include<iostream>
using namespace std;

// 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() {

// Created an object of class C


C obj;

// Calling function func() in class A


obj.A::func();

// Calling function func() in class B


obj.B::func();

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.

Feature Aggregation Inheritance

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).

Type of HAS-A IS-A (hierarchical)


Relationship (composition-like)
High, as the child
Limited, as only class inherits all
Code properties and
object access is
Reusability methods of the
provided.
parent class.

Loose coupling Tight coupling


Coupling (objects exist (child class depends
independently). on the parent class).

More flexible; can Less flexible;


modify components changing the parent
Flexibility class may impact
without affecting the
main class. child classes.

When objects need When a class needs


to interact but to extend or
Use Case specialize another
maintain their own
lifecycle. class.

Memory More memory Less memory


Usage efficient; avoids efficient due to
Feature Aggregation Inheritance

unnecessary redundant inherited


property inheritance. attributes.

Requires explicitly Automatically


Method inherits and can
calling the contained
Access override methods.
object's methods.

#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.

An abstract class is a class that cannot be instantiated and serves as a


blueprint for other classes. It may contain abstract methods (methods
without implementations) that must be implemented in derived (child)
classes.

A pure virtual function (or abstract function) in C++ is a virtual function


for which we can have an implementation, But we must override that
function in the derived class, otherwise, the derived class will also
become an abstract class. A pure virtual function is declared by
assigning 0 in the declaration.

Key Features of an Abstract Class:


1. Cannot be instantiated – Objects of an abstract class cannot be
created directly.
2. Can have abstract methods – These must be implemented in child
classes.
3. Can have concrete methods – These provide default
implementations that can be inherited.
4. Supports Inheritance – Child classes use the extends keyword (in
Java) or : (in C++) to inherit.
5. Can have instance variables – Unlike interfaces, an abstract class
can define instance variables.
6. Encapsulation and Code Reusability – Can contain private variables
and methods.

#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:

 Animal is an abstract class because it has a pure virtual function


(makeSound()).
 Doginherits from Animal and implementsmakeSound().
 We cannot create an Animal object, but we can create a Dog object.
When to Use an Abstract Class?
 When you want to enforce a structure in child classes.
 When a base class should not be instantiated but should provide
common functionality.
 When multiple subclasses share behavior but need to define
specific implementations.

Q 6.
Explain the concept of interfaces and abstract class in detail.

An interface is a collection of abstract methods that define a contract for


implementing classes. Unlike an abstract class, an interface cannot
contain concrete methods (before Java 8) and does not contain instance
variables.
Features of Interfaces:

1. Cannot have instance variables – All variables are implicitly


public static final.
2. Only abstract methods (before Java 8) – Methods must be
implemented in the implementing class.
3. Multiple Inheritance Support – A class can implement multiple
interfaces.
4. Defines a contract – Any class that implements an interface must
define all its methods.
5. Uses implements Keyword – Instead of extends, interfaces use
implements for implementation.
6. From Java 8 onwards: Interfaces can have default and static
methods.

Example of Abstract Class in Java


abstract class Animal {
abstract void makeSound(); // Abstract method (must be
overridden)

void sleep() { // Concrete method


System.out.println("Sleeping...");
}
}

class Dog extends Animal {


void makeSound() {
System.out.println("Dog barks: Woof Woof!");
}
}

public class Main {


public static void main(String[] args) {
// Animal a = new Animal(); // ERROR: Cannot instantiate
an abstract class
Dog d = new Dog();
d.makeSound();
d.sleep();
}
}
Example of an Interface in Java

interface Animal {
void makeSound(); // Abstract method (implicitly public &
abstract)
}

class Dog implements Animal {


public void makeSound() { // Must be public
System.out.println("Dog barks: Woof Woof!");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
d.makeSound();
}
}
Differences: Abstract Class vs. Interface

Feature Abstract Class Interface

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)

Access Methods can have any modifier


Methods are public by default
Modifiers (private, protected, public)

Multiple (a class can


Supports multiple inheritance
Does not support multiple inheritance
Inheritance implement multiple interfaces)

Used for base classes with shared Used for defining behavior contracts
Use Case
behavior without implementation
Feature Abstract Class Interface

Keyword Used extends implements

Example: Abstract Class + Interface Together

// Abstract Class
abstract class Animal {
abstract void makeSound();
void sleep() {
System.out.println("Sleeping...");
}
}

// Interface
interface Pet {
void play();
}

// Dog inherits Animal (abstract class) and implements Pet


(interface)
class Dog extends Animal implements Pet {
void makeSound() {
System.out.println("Dog barks: Woof Woof!");
}

public void play() {


System.out.println("Dog is playing...");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
d.makeSound(); // From Animal class
d.sleep(); // Inherited from Animal class
d.play(); // Implemented from Pet interface
}
}

1. Use an abstract class when creating a base class with default


behavior.
2. Use an interface when defining a contract for multiple unrelated
classes to implement.
3. Use both when a class needs to extend behavior and follow a contract.
Q 7.
Explain Generalization and Specialization in OOP in detail.
Generalization and specialization are two fundamental concepts in
inheritance that define the relationship between parent and child classes
in Object-Oriented Programming (OOP).

1. Generalization (Bottom-Up Approach)

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...");
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car();
myCar.start(); // Inherited from Vehicle
myCar.drive();
}
}

2Specialization (Top-Down Approach)


Definition:
 Specialization is the opposite of generalization. It is a top-down
approach where a parent class is specialized into more specific
child classes by adding unique features.
 It is used when we need to add specific behavior to subclasses.

Example:

 A Vehicle can be specialized into Car and Truck, with additional


features added to each subclass.

// 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.");
}
}

class Manager extends Employee {


void manageTeam() {
System.out.println(name + " is managing the team.");
}
}

public class Main {


public static void main(String[] args) {
Developer dev = new Developer();
dev.name = "Alice";
dev.work(); // Inherited from Employee
dev.code(); // Specialized method

Manager mgr = new Manager();


mgr.name = "Bob";
mgr.work(); // Inherited from Employee
mgr.manageTeam(); // Specialized method
}
}

Comparison: Generalization vs. Specialization

Feature Generalization Specialization

Creating specialized
Extracting common features to create a
Definition subclasses by adding unique
generalized superclass.
features.

Approach Bottom-Up Top-Down

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.

Employee is specialized into


Example Car and Truck become Vehicle.
Developer and Manager.

You might also like