Assignment- 2
Name- HARSH PRAJAPATI
Registration no.- 23BCY10314
1.what is inheritance discuss in detail about the various
type of inheritance in C++?
Ans. Inheritance is a fundamental concept in object-oriented programming
(OOP) that allows a class to inherit properties and behaviors (methods) from
another class. In C++, inheritance is used to promote code reuse and
establish a natural hierarchical relationship between classes.
Types of Inheritance in C++
Single Inheritance:
A class inherits from one base class.
Simplifies the class hierarchy and is easy to manage.
Multiple Inheritance:
A class inherits from more than one base class.
Multilevel Inheritance:
A class is derived from another derived class.
Forms a chain of inheritance.
Hierarchical Inheritance:
Multiple derived classes inherit from a single base class.
Useful when different derived classes share common functionality from
a base class.
Hybrid Inheritance:
A combination of two or more types of inheritance.
Can create complex and sophisticated class hierarchies but also risks
ambiguity and complexity.
Inheritance in C++ is a powerful feature that promotes code reuse and
establishes relationships between classes. Understanding the different types
of inheritance and how to manage complexities such as the diamond
problem is crucial for effective OOP in C++.
2.what is virtual function explain with an example how
late binding energy using virtual function?
Ans. A virtual function in C++ is a member function in a base class that you
expect to be redefined in derived classes. When you use virtual functions,
you enable polymorphism, which allows a program to decide at runtime
which function to call, rather than at compile time. This concept is also
known as late binding or dynamic binding.
How Virtual Functions Enable Late Binding
Late binding means that the function call is not resolved until runtime. This
is in contrast to early binding, where the function call is resolved at compile
time. Virtual functions facilitate late binding through the use of a vtable
(virtual table), which is a mechanism that stores function pointers.
Detailed Explanation
1. Base Class and Derived Classes:
o You have a base class Animal with a virtual function makeSound().
o Two derived classes, Dog and Cat, override this virtual function to
provide their specific implementations.
2. Creating Objects:
o You create an object of the Dog class and an object of the Cat class.
3. Pointer of Base Class Type:
o You create a pointer of type Animal.
o This pointer can point to any object of a class derived from Animal.
4. Assigning Objects to Pointer:
o First, you assign the Dog object to the Animal pointer and call the
makeSound() function.
o The program checks the vtable for the Dog class and calls the Dog's
version of makeSound().
o Next, you assign the Cat object to the Animal pointer and call the
makeSound() function.
o The program checks the vtable for the Cat class and calls the Cat's
version of makeSound().
Conceptual Steps:
1. Base Class Definition:
o Define a base class Animal with a virtual function makeSound().
2. Derived Class Definitions:
o Define derived classes Dog and Cat that override the makeSound()
function.
3. Polymorphism Setup:
o Use a pointer of type Animal to point to objects of Dog and Cat.
4. Dynamic Function Call:
o When makeSound() is called through the Animal pointer, the program
dynamically binds to the correct function implementation based on the
actual object type (either Dog or Cat).
Conclusion
Virtual functions enable late binding by using the vtable mechanism,
allowing the program to select the appropriate function implementation at
runtime based on the actual object type. This facilitates polymorphism,
making the code more flexible and easier to extend.
3.Explain class object to base and base to class object
conversion using C++ with suitable example?
Ans. In C++, converting between derived class objects and base class
objects can involve both implicit and explicit conversions. Understanding
these conversions is crucial for handling polymorphism and inheritance
properly. Let's explore these conversions with suitable examples.
Class Object to Base Class Object Conversion
When you derive a class from a base class, you can implicitly convert a
derived class object to a base class object. This is because the derived class
is a specialized version of the base class and thus contains all its members.
#include <iostream>
class Base {
public:
void baseFunction() {
std::cout << "Function in Base class" << std::endl;
}
};
class Derived : public Base {
public:
void derivedFunction() {
std::cout << "Function in Derived class" << std::endl;
}
};
int main() {
Derived derivedObj;
Base baseObj = derivedObj; // Implicit conversion from Derived to Base
baseObj.baseFunction();
// baseObj.derivedFunction(); // Error: Base class doesn't have derivedFunction
return 0;
}
Base Class Pointer to Derived Class Pointer Conversion
When dealing with pointers, you can assign a base class pointer to point to a
derived class object. This allows polymorphic behavior.
#include <iostream>
class Base {
public:
virtual void show() {
std::cout << "Base class show function" << std::endl;
}
};
class Derived : public Base {
public:
void show() override {
std::cout << "Derived class show function" << std::endl;
}
};
int main() {
Derived derivedObj;
Base* basePtr = &derivedObj; // Base class pointer pointing to Derived class object
basePtr->show(); // Calls the overridden show() function in Derived class
return 0;
}
Base Class Object to Derived Class Object Conversion
Converting a base class object to a derived class object is not
straightforward and generally requires an explicit cast. This is often done
using dynamic_cast when dealing with pointers or references, ensuring that the
conversion is safe.
#include <iostream>
class Base {
public:
virtual void show() {
std::cout << "Base class show function" << std::endl;
}
};
class Derived : public Base {
public:
void show() override {
std::cout << "Derived class show function" << std::endl;
}
void derivedFunction() {
std::cout << "Function in Derived class" << std::endl;
}
};
int main() {
Base* basePtr = new Derived(); // Base class pointer pointing to Derived class object
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // Explicit conversion using
dynamic_cast
if (derivedPtr) {
derivedPtr->derivedFunction(); // Safe to call derived class functions
} else {
std::cout << "Conversion failed" << std::endl;
}
delete basePtr;
return 0;
}
4.Write a C + + code to construct class of a person
with name age as public properties account detail as
a private properties and a percentage of marks is
protected from the constructor class with a sport
detail of person constructor class to rank person
based on the equal weightage to academic and and
sports detail using inheritance operator.
Ans. #include <iostream>
#include <string>
using namespace std;
// Base class Person
class Person {
public:
string name;
int age;
double percentageOfMarks;
Person(string n, int a, double marks, string accDetail)
: name(n), age(a), percentageOfMarks(marks), accountDetail(accDetail) {}
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Academic Marks: " << percentageOfMarks << "%" << endl;
}
private:
string accountDetail;
};
// Base class SportsDetail
class SportsDetail {
public:
double sportsScore;
SportsDetail(double score) : sportsScore(score) {}
void displaySports() {
cout << "Sports Score: " << sportsScore << endl;
}
};
// Derived class RankedPerson
class RankedPerson : public Person, public SportsDetail {
public:
double overallScore;
RankedPerson(string n, int a, double marks, string accDetail, double sports)
: Person(n, a, marks, accDetail), SportsDetail(sports) {
calculateOverallScore();
}
void calculateOverallScore() {
overallScore = (percentageOfMarks + sportsScore) / 2;
}
void displayRank() {
display();
displaySports();
cout << "Overall Score: " << overallScore << endl;
}
};
int main() {
RankedPerson person1("John Doe", 20, 85.0, "123456789", 90.0);
RankedPerson person2("Jane Smith", 22, 78.0, "987654321", 85.0);
cout << "Person 1 Details:" << endl;
person1.displayRank();
cout << endl;
cout << "Person 2 Details:" << endl;
person2.displayRank();
cout << endl;
if (person1.overallScore > person2.overallScore) {
cout << "Person 1 ranks higher." << endl;
} else if (person1.overallScore < person2.overallScore) {
cout << "Person 2 ranks higher." << endl;
} else {
cout << "Both persons have the same rank." << endl;
}
return 0;
}
5. What are abstract class give an example to illustrate
the use of abstract class?
Ans. An abstract class in C++ is a class that cannot be instantiated and is
typically used as a base class. It contains at least one pure virtual function,
which is a function declared by placing = 0 at the end of its declaration.
Abstract classes are used to define interfaces that derived classes must
implement.
#include <iostream>
#include <string>
using namespace std;
// Abstract base class
class Animal {
public:
virtual void makeSound() const = 0; // Pure virtual function
void move() const {
cout << "The animal moves." << endl;
}
};
// Derived class Dog from the abstract base class Animal
class Dog : public Animal {
public:
void makeSound() const override {
cout << "The dog barks: Woof Woof!" << endl;
}
};
// Derived class Cat from the abstract base class Animal
class Cat : public Animal {
public:
void makeSound() const override {
cout << "The cat meows: Meow Meow!" << endl;
}
};
int main() {
Dog myDog;
Cat myCat;
Animal* animals[] = { &myDog, &myCat };
for (Animal* animal : animals) {
animal->makeSound();
animal->move();
}
return 0;
}