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

Unit 4 All Programs

C++ programs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Unit 4 All Programs

C++ programs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

UNIT – 4 : ALL PROGRAMS

PREPARE WELL FOR SECOND INTERNAL EXAM


Operator Overloading in C++

#include <iostream>

using namespace std;

// Class to demonstrate operator overloading

class Complex {

private:

float real, imag;

public:

// Constructor

Complex(float r = 0, float i = 0) : real(r), imag(i) {}

// Overload the + operator

Complex operator+(const Complex& other) {

return Complex(real + other.real, imag + other.imag);

// Function to display the complex number

void display() const {

cout << real << " + " << imag << "i" << endl;

};

int main() {

// Create two Complex objects

Complex c1(3.4, 5.2), c2(1.6, 2.8);

// Add two complex numbers using overloaded +

Complex c3 = c1 + c2;

// Display the result

cout << "c1 = ";


c1.display();

cout << "c2 = ";

c2.display();

cout << "c1 + c2 = ";

c3.display();

return 0;

Explanation:

1. Constructor: Initializes the real and imaginary parts of the complex number.

2. Operator Overloading:

o The operator+ function is a member function that takes a const Complex& as an


argument.

o It creates and returns a new Complex object with the sum of the real and imaginary
parts.

3. Display Function: Prints the complex number in a readable format.

4. Main Function:

o Creates two Complex objects (c1 and c2).

o Adds c1 and c2 using the overloaded + operator.

o Displays the result.

Output:

c1 = 3.4 + 5.2i

c2 = 1.6 + 2.8i

c1 + c2 = 5 + 8i
Operator Overloading Using Friend Functions

#include <iostream>

using namespace std;

// Class to demonstrate operator overloading using friend functions

class Complex {

private:

float real, imag;

public:

// Constructor

Complex(float r = 0, float i = 0) : real(r), imag(i) {}

// Friend function to overload the + operator

friend Complex operator+(const Complex& c1, const Complex& c2);

// Function to display the complex number

void display() const {

cout << real << " + " << imag << "i" << endl;

};

// Overloading the + operator using a friend function

Complex operator+(const Complex& c1, const Complex& c2) {

return Complex(c1.real + c2.real, c1.imag + c2.imag);

int main() {

// Create two Complex objects

Complex c1(3.5, 2.7), c2(1.4, 3.3);

// Add two complex numbers using overloaded +

Complex c3 = c1 + c2;

// Display the results

cout << "c1 = ";

c1.display();
cout << "c2 = ";

c2.display();

cout << "c1 + c2 = ";

c3.display();

return 0;

Explanation:

1. Constructor: Initializes the real and imaginary parts of the complex number.

2. Friend Function:

o The operator+ function is declared as a friend inside the class.

o This allows the function to access private members (real and imag) of the Complex
class.

o The function takes two const Complex& arguments and returns a new Complex
object containing the sum of the operands.

3. Display Function: Outputs the complex number in a readable format.

4. Main Function:

o Creates two Complex objects (c1 and c2).

o Adds c1 and c2 using the overloaded + operator.

o Displays the result.

OUTPUT:

c1 = 3.5 + 2.7i

c2 = 1.4 + 3.3i

c1 + c2 = 4.9 + 6i

Advantages of Using Friend Functions:

• Enables operator overloading where the left-hand operand is not an object of the class.

• Simplifies the access to private and protected members without needing additional getter
methods.
INHERITANCE
Single Inheritance: A class inherits from one base class.

#include <iostream>

using namespace std;

// Base class

class Parent {

public:

void displayParent() {

cout << "This is the Parent class (Base)." << endl;

};

// Derived class

class Child : public Parent {

public:

void displayChild() {

cout << "This is the Child class (Derived)." << endl;

};

int main() {

Child obj;

obj.displayParent();

obj.displayChild();

return 0;

OUTPUT:

This is the Parent class (Base).

This is the Child class (Derived).


Multiple Inheritance: A class inherits from more than one base class.

#include <iostream>

using namespace std;

// First base class

class Base1 {

public:

void displayBase1() {

cout << "This is Base1 class." << endl;

} };

// Second base class

class Base2 {

public:

void displayBase2() {

cout << "This is Base2 class." << endl;

};

// Derived class

class Derived : public Base1, public Base2 {

public:

void displayDerived() {

cout << "This is the Derived class (Multiple Inheritance)." << endl;

};

int main() {

Derived obj;

obj.displayBase1();

obj.displayBase2();

obj.displayDerived();

return 0;

}
OUTPUT:

This is Base1 class.

This is Base2 class.

This is the Derived class (Multiple Inheritance).

Hierarchical Inheritance: Multiple classes inherit from a single base class.

#include <iostream>

using namespace std;

// Base class

class Parent {

public:

void displayParent() {

cout << "This is the Parent class (Base)." << endl;

};

// First derived class

class Child1 : public Parent {

public:

void displayChild1() {

cout << "This is Child1 class." << endl;

};

// Second derived class

class Child2 : public Parent {

public:

void displayChild2() {

cout << "This is Child2 class." << endl;

} };
int main() {

Child1 obj1;

Child2 obj2;

obj1.displayParent();

obj1.displayChild1();

obj2.displayParent();

obj2.displayChild2();

return 0;

OUTPUT:

This is the Parent class (Base).

This is Child1 class.

This is the Parent class (Base).

This is Child2 class.

Multilevel Inheritance: A class inherits from a derived class, creating a chain.

#include <iostream>

using namespace std;

// Base class

class Grandparent {

public:

void displayGrandparent() {

cout << "This is the Grandparent class." << endl;

};

// Intermediate class

class Parent : public Grandparent {

public:

void displayParent() {

cout << "This is the Parent class." << endl; } };


// Derived class

class Child : public Parent {

public:

void displayChild() {

cout << "This is the Child class (Multilevel Inheritance)." << endl;

};

int main() {

Child obj;

obj.displayGrandparent();

obj.displayParent();

obj.displayChild();

return 0;

OUTPUT:

This is the Grandparent class.

This is the Parent class.

This is the Child class (Multilevel Inheritance).

Hybrid Inheritance: A combination of two or more types of inheritance.

#include <iostream>

using namespace std;

// Base class

class Base {

public:

void displayBase() {
cout << "This is the Base class." << endl;

};

// First derived class

class Derived1 : public Base {

public:

void displayDerived1() {

cout << "This is Derived1 class." << endl;

};

// Second derived class

class Derived2 : public Base {

public:

void displayDerived2() {

cout << "This is Derived2 class." << endl;

};

// Final derived class

class Final : public Derived1, public Derived2 {

public:

void displayFinal() {

cout << "This is the Final class (Hybrid Inheritance)." << endl;

};

int main() {

Final obj;

// Access ambiguity must be resolved explicitly


obj.Derived1::displayBase();

obj.displayDerived1();

obj.displayDerived2();

obj.displayFinal();

return 0;

OUTPUT:

This is the Base class.

This is Derived1 class.

This is Derived2 class.

This is the Final class (Hybrid Inheritance).

6 MULITI PATH INHERITANCE

#include <iostream>
using namespace std;

// Base class
class Base {
public:
void displayBase() {
cout << "This is the Base class." << endl;
}
};

// Intermediate classes inheriting the Base class


class Derived1 : virtual public Base {
};

class Derived2 : virtual public Base {


};

// Final derived class inheriting both Derived1 and Derived2


class Final : public Derived1, public Derived2 {
public:
void displayFinal() {
cout << "This is the Final class (Multipath Inheritance)." << endl;
}
};
int main() {
Final obj;
obj.displayBase(); // Ambiguity is resolved using virtual inheritance
obj.displayFinal();
return 0;
}

OUTPUT:
This is the Base class.
This is the Final class (Multipath Inheritance).

This following program just for reference and not for exam
1 program with 5 inheritance

#include <iostream>

using namespace std;

// Base Class

class Base {

public:

void showBase() {

cout << "This is the Base class." << endl;

};

// 1. Single Inheritance

class SingleDerived : public Base {

public:

void showSingle() {

cout << "This is SingleDerived class (Single Inheritance)." << endl;

};
// 2. Multiple Inheritance

class ClassA {

public:

void showA() {

cout << "This is ClassA (part of Multiple Inheritance)." << endl;

};

class ClassB {

public:

void showB() {

cout << "This is ClassB (part of Multiple Inheritance)." << endl;

};

class MultipleDerived : public ClassA, public ClassB {

public:

void showMultiple() {

cout << "This is MultipleDerived class (Multiple Inheritance)." << endl;

};

// 3. Hierarchical Inheritance

class HierarchicalDerived1 : public Base {

public:

void showHierarchical1() {

cout << "This is HierarchicalDerived1 class (Hierarchical Inheritance)." << endl;

};

class HierarchicalDerived2 : public Base {


public:

void showHierarchical2() {

cout << "This is HierarchicalDerived2 class (Hierarchical Inheritance)." << endl;

};

// 4. Multilevel Inheritance

class Intermediate : public Base {

public:

void showIntermediate() {

cout << "This is Intermediate class (part of Multilevel Inheritance)." << endl;

};

class MultilevelDerived : public Intermediate {

public:

void showMultilevel() {

cout << "This is MultilevelDerived class (Multilevel Inheritance)." << endl;

};

// 5. Hybrid Inheritance

class HybridDerived : public Base, public ClassA {

public:

void showHybrid() {

cout << "This is HybridDerived class (Hybrid Inheritance)." << endl;

};

int main() {

// Demonstrate Single Inheritance


SingleDerived singleObj;

singleObj.showBase();

singleObj.showSingle();

// Demonstrate Multiple Inheritance

MultipleDerived multipleObj;

multipleObj.showA();

multipleObj.showB();

multipleObj.showMultiple();

// Demonstrate Hierarchical Inheritance

HierarchicalDerived1 hierarchicalObj1;

hierarchicalObj1.showBase();

hierarchicalObj1.showHierarchical1();

HierarchicalDerived2 hierarchicalObj2;

hierarchicalObj2.showBase();

hierarchicalObj2.showHierarchical2();

// Demonstrate Multilevel Inheritance

MultilevelDerived multilevelObj;

multilevelObj.showBase();

multilevelObj.showIntermediate();

multilevelObj.showMultilevel();

// Demonstrate Hybrid Inheritance

HybridDerived hybridObj;

hybridObj.showBase();

hybridObj.showA();

hybridObj.showHybrid();
return 0;

Explanation:

1. Single Inheritance:

o SingleDerived inherits from Base and can access its members.

2. Multiple Inheritance:

o MultipleDerived inherits from ClassA and ClassB.

3. Hierarchical Inheritance:

o Both HierarchicalDerived1 and HierarchicalDerived2 inherit from Base.

4. Multilevel Inheritance:

o Intermediate inherits from Base, and MultilevelDerived inherits from Intermediate.

5. Hybrid Inheritance:

o HybridDerived inherits from both Base and ClassA.

OUTPUT:

This is the Base class.

This is SingleDerived class (Single Inheritance).

This is ClassA (part of Multiple Inheritance).

This is ClassB (part of Multiple Inheritance).

This is MultipleDerived class (Multiple Inheritance).

This is the Base class.

This is HierarchicalDerived1 class (Hierarchical Inheritance).

This is the Base class.

This is HierarchicalDerived2 class (Hierarchical Inheritance).

This is the Base class.

This is Intermediate class (part of Multilevel Inheritance).

This is MultilevelDerived class (Multilevel Inheritance).

This is the Base class.

This is ClassA (part of Multiple Inheritance).

This is HybridDerived class (Hybrid Inheritance).


VIRTUAL BASE CLASS
#include <iostream>

using namespace std;

// Base class

class Base {

public:

void displayBase() {

cout << "This is the Base class." << endl;

};

// Derived classes from Base (with virtual inheritance)

class Derived1 : virtual public Base {

public:

void displayDerived1() {

cout << "This is Derived1 class." << endl;

};

class Derived2 : virtual public Base {

public:

void displayDerived2() {

cout << "This is Derived2 class." << endl;

};

// Final derived class inheriting from Derived1 and Derived2

class Final : public Derived1, public Derived2 {

public:

void displayFinal() {
cout << "This is the Final class." << endl;

};

int main() {

Final obj;

// Accessing members

obj.displayBase(); // No ambiguity due to virtual inheritance

obj.displayDerived1();

obj.displayDerived2();

obj.displayFinal();

return 0;

Explanation:

1. Virtual Inheritance:

o The Derived1 and Derived2 classes inherit from the Base class virtually using the
virtual keyword.

o This ensures that Final class inherits only one copy of the Base class, avoiding
ambiguity.

2. Diamond Problem:

o Without virtual inheritance, the Base class would be inherited twice into Final (once
via Derived1 and once via Derived2), causing ambiguity when accessing members of
Base.

3. No Ambiguity:

o Virtual inheritance eliminates multiple copies of the Base class, ensuring only one
shared copy is inherited.

Output:

This is the Base class.

This is Derived1 class.


This is Derived2 class.

This is the Final class.

Key Points:

• Use virtual inheritance when a class appears multiple times in an inheritance hierarchy to
prevent multiple copies of the base class.

• Virtual inheritance is particularly useful in solving the diamond problem.

Abstract Class in C++


#include <iostream>

using namespace std;

// Abstract base class

class Shape {

public:

// Pure virtual function

virtual void draw() = 0;

// Virtual function with implementation

virtual void displayInfo() {

cout << "This is a shape." << endl;

// Destructor

virtual ~Shape() {

cout << "Shape destructor called." << endl;

};

// Derived class 1
class Circle : public Shape {

public:

void draw() override {

cout << "Drawing a Circle." << endl;

};

// Derived class 2

class Rectangle : public Shape {

public:

void draw() override {

cout << "Drawing a Rectangle." << endl;

};

int main() {

// Cannot instantiate abstract class

// Shape shape; // Error: Shape is abstract

// Create pointers to derived classes

Shape* shape1 = new Circle();

Shape* shape2 = new Rectangle();

// Call overridden methods

shape1->draw();

shape1->displayInfo();

shape2->draw();

shape2->displayInfo();

// Clean up
delete shape1;

delete shape2;

return 0;

Explanation:

1. Abstract Base Class (Shape):

o The Shape class has a pure virtual function draw() declared using virtual void draw()
= 0;.

o A class containing at least one pure virtual function is considered an abstract class.

o Abstract classes cannot be instantiated directly.

2. Derived Classes (Circle and Rectangle):

o These classes provide their own implementation of the draw() function.

o Derived classes are concrete classes and can be instantiated.

3. Dynamic Polymorphism:

o A base class pointer (Shape*) is used to call the draw() function on derived class
objects.

o This demonstrates runtime polymorphism (function overriding).

4. Destructor:

o A virtual destructor ensures proper cleanup when deleting objects via a base class
pointer.

Output:

Drawing a Circle.

This is a shape.

Drawing a Rectangle.

This is a shape.

Shape destructor called.

Shape destructor called.

Key Points:
• Abstract classes provide a blueprint for derived classes.

• Derived classes must override pure virtual functions, or they themselves become abstract.

• Abstract classes are commonly used to define interfaces in C++.

Constructors in Derived Classes

#include <iostream>

using namespace std;

// Base class

class Base {

public:

Base() {

cout << "Base class constructor called." << endl;

};

// Derived class

class Derived : public Base {

public:

Derived() {

cout << "Derived class constructor called." << endl;

};

int main() {

Derived obj; // Calls Base and then Derived constructor

return 0;

Output:

Base class constructor called.


Derived class constructor called.

Member Class: Nesting of Classes

#include <iostream>

using namespace std;

class Outer {

public:

class Inner {

public:

void display() {

cout << "This is the Inner class." << endl;

};

void show() {

cout << "This is the Outer class." << endl;

};

int main() {

Outer::Inner objInner;

objInner.display();

Outer objOuter;

objOuter.show();

return 0;

Output:

This is the Inner class.


This is the Outer class.

Pointer to Objects

#include <iostream>

using namespace std;

class MyClass {

public:

void display() {

cout << "Pointer to object example." << endl;

};

int main() {

MyClass obj;

MyClass* ptr = &obj; // Pointer to object

ptr->display();

return 0;

Output:

Pointer to object example.

this Pointer

#include <iostream>

using namespace std;

class MyClass {

public:

void display() {

cout << "The address of this object is: " << this << endl;

}
};

int main() {

MyClass obj;

obj.display();

return 0;

Output:

The address of this object is: <address>

Pointer to Derived Class

#include <iostream>

using namespace std;

class Base {

public:

virtual void display() {

cout << "Base class display function." << endl;

};

class Derived : public Base {

public:

void display() override {

cout << "Derived class display function." << endl;

};

int main() {

Base* basePtr;
Derived derivedObj;

basePtr = &derivedObj;

basePtr->display(); // Calls Derived's display (virtual)

return 0;

Output:

Derived class display function.

Virtual Functions

#include <iostream>

using namespace std;

class Base {

public:

virtual void display() {

cout << "Base class virtual function." << endl;

};

class Derived : public Base {

public:

void display() override {

cout << "Derived class overriding virtual function." << endl;

};

int main() {

Base* ptr;

Derived obj;
ptr = &obj;

ptr->display(); // Calls Derived's display function

return 0;

Output:

Derived class overriding virtual function.

Pure Virtual Functions

#include <iostream>

using namespace std;

class AbstractBase {

public:

virtual void display() = 0; // Pure virtual function

};

class Derived : public AbstractBase {

public:

void display() override {

cout << "Derived class implementing pure virtual function." << endl;

};

int main() {

Derived obj;

obj.display();

return 0;

}
Output:

Derived class implementing pure virtual function.

Polymorphism

#include <iostream>

using namespace std;

class Shape {

public:

virtual void draw() {

cout << "Drawing a shape." << endl;

};

class Circle : public Shape {

public:

void draw() override {

cout << "Drawing a Circle." << endl;

};

class Rectangle : public Shape {

public:

void draw() override {

cout << "Drawing a Rectangle." << endl;

};

int main() {

Shape* shape;
Circle circleObj;

Rectangle rectangleObj;

shape = &circleObj;

shape->draw(); // Calls Circle's draw()

shape = &rectangleObj;

shape->draw(); // Calls Rectangle's draw()

return 0;

Output:

Drawing a Circle.

Drawing a Rectangle.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy