C++ Programs

 CLICK TO DOWNLOAD

https://www.mediafire.com/file/ib4morqnimr7vqb/p3.txt/file

Codes

**7.a) Write a C++ Program that illustrate single inheritance.**  

```cpp

#include <iostream>

using namespace std;


class Animal {

public:

    virtual void eat() {

        cout << "Animal is eating food" << endl;

    }

};


class Dog : public Animal {

public:

    void bark() {

        cout << "Woof!" << endl;

    }


    void eat() override {

        Animal::eat();

        cout << "Dog is also enjoying some treats!" << endl;

    }

};


class Cat : public Animal {

public:

    void meow() {

        cout << "Meow!" << endl;

    }

};


int main() {

    Dog dog;

    cout << "Dog object calling inherited eat() method:" << endl;

    dog.eat();


    cout << "Dog object calling its own bark() method:" << endl;

    dog.bark();


    Cat cat;

    cout << "Cat object calling inherited eat() method:" << endl;

    cat.eat();


    cout << "Cat object calling its own meow() method:" << endl;

    cat.meow();


    return 0;

}

```


---


**7.b) Write a C++ Program that illustrate multiple inheritance.**  

```cpp

#include <iostream>

using namespace std;


class Shape {

public:

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

};


class TwoDimensionalShape : public virtual Shape {

public:

    int width, height;

};


class ThreeDimensionalShape : public virtual Shape {

public:

    int length, width, height;

};


class Rectangle : public TwoDimensionalShape {

public:

    Rectangle(int w, int h) {

        width = w;

        height = h;

    }


    void calculateArea() override {

        cout << "Area of rectangle: " << width * height << endl;

    }

};


class Cube : public ThreeDimensionalShape {

public:

    Cube(int l) {

        length = l;

    }


    void calculateArea() override {

        cout << "Surface area of cube: " << 6 * length * length << endl;

    }

};


int main() {

    Rectangle rectangle(5, 3);

    rectangle.calculateArea();


    Cube cube(4);

    cube.calculateArea();


    return 0;

}

```


---


**7.c) Write a C++ Program that illustrate multi level inheritance.**  

```cpp

#include <iostream>

using namespace std;


// Base class

class Vehicle {

public:

    void vehicle() {

        cout << "I am a vehicle." << endl;

    }

};


// Derived class inheriting from Vehicle

class FourWheeler : public Vehicle {

public:

    void fourWheeler() {

        cout << "I have four wheels." << endl;

    }

};


// Derived class inheriting from FourWheeler

class Car : public FourWheeler {

public:

    void car() {

        cout << "I am a car." << endl;

    }

};


int main() {

    Car obj;

    obj.vehicle(); // Accessing method from Vehicle

    obj.fourWheeler(); // Accessing method from FourWheeler

    obj.car(); // Accessing method from Car


    return 0;

}

```


---


**7.d) Write a C++ Program that illustrate Hierarchical inheritance.**  

```cpp

#include <iostream>

#include <string>

using namespace std;


// Base class

class Animal {

public:

    string name;


    // Constructor for Animal class

    Animal(const string& animalName) : name(animalName) {}


    void eat() {

        cout << "I am eating." << endl;

    }

};


// Derived class 1

class Mammal : public Animal {

public:

    // Constructor for Mammal class

    Mammal(const string& animalName) : Animal(animalName) {}


    void giveBirth() {

        cout << "I give birth to live young." << endl;

    }

};


// Derived class 2

class Bird : public Animal {

public:

    // Constructor for Bird class

    Bird(const string& animalName) : Animal(animalName) {}


    void layEggs() {

        cout << "I lay eggs." << endl;

    }

};


int main() {

    Mammal myFeistyFeline("Whiskers");

    cout << "My cat " << myFeistyFeline.name << " is hungry after a long nap." << endl;

    myFeistyFeline.eat();

    myFeistyFeline.giveBirth();


    Bird myChattyParrot("Polly");

    cout << "My parrot " << myChattyParrot.name << " is enjoying a tasty seed snack." << endl;

    myChattyParrot.eat();

    myChattyParrot.layEggs();


    return 0;

}

```



Here are the codes with question names starting from question 9:


---


**9) Student, Test, Sports, and Result Classes Inheritance**  

```cpp

#include <iostream>

using namespace std;


// Base Class: Student

class Student {

protected:

    int rollNo;

public:

    void setRollNo(int r) {

        rollNo = r;

    }

    void displayRollNo() const {

        cout << "Roll No: " << rollNo << endl;

    }

};


// Derived Class: Test

class Test : public Student {

protected:

    int subjectScores[5];

    int totalTestScore = 0;

public:

    void setSubjectScores() {

        cout << "Enter scores for 5 subjects: ";

        for (int i = 0; i < 5; i++) {

            cin >> subjectScores[i];

            totalTestScore += subjectScores[i];

        }

    }

    void displayTestScores() const {

        cout << "Scores in Subjects: ";

        for (int i = 0; i < 5; i++) {

            cout << subjectScores[i] << " ";

        }

        cout << "\nTotal Test Score: " << totalTestScore << endl;

    }

};


// Derived Class: Sports

class Sports : public Student {

protected:

    int sportsScore = 0;

public:

    void setSportsScore() {

        cout << "Enter score in Sports: ";

        cin >> sportsScore;

    }

    void displaySportsScore() const {

        cout << "Sports Score: " << sportsScore << endl;

    }

};


// Derived Class: Result

class Result : public Test, public Sports {

public:

    void displayFinalResult() const {

        int totalScore = totalTestScore + sportsScore;

        displayRollNo();

        displayTestScores();

        displaySportsScore();

        cout << "Total Score: " << totalScore << endl;

    }

};


int main() {

    Result student;

    int rollNumber;

    cout << "Enter Roll Number: ";

    cin >> rollNumber;

    student.setRollNo(rollNumber);

    student.setSubjectScores();

    student.setSportsScore();

    student.displayFinalResult();

    return 0;

}

```


---


**10) Eldest Person Using 'this' Pointer**  

```cpp

#include <iostream>

#include <string>

using namespace std;


class Person {

private:

    string name;

    int age;

public:

    Person(string n, int a) : name(n), age(a) {}

    void displayDetails() const {

        cout << "Name: " << name << ", Age: " << age << endl;

    }

    Person* findEldest(Person* otherPerson) {

        return (this->age > otherPerson->age) ? this : otherPerson;

    }

};


int main() {

    Person person1("John", 25);

    Person person2("Alice", 30);

    cout << "Person 1: "; person1.displayDetails();

    cout << "Person 2: "; person2.displayDetails();

    Person* eldest = person1.findEldest(&person2);

    cout << "\nEldest Person: "; eldest->displayDetails();

    return 0;

}

```


---


**11a) Virtual Functions Example**  

```cpp

#include <iostream>

using namespace std;


class Shape {

public:

    virtual void draw() { cout << "Drawing Shape" << endl; }

};


class Circle : public Shape {

public:

    void draw() override { cout << "Drawing Circle" << endl; }

};


class Rectangle : public Shape {

public:

    void draw() override { cout << "Drawing Rectangle" << endl; }

};


int main() {

    Shape* shape1;

    Circle circle;

    Rectangle rectangle;

    shape1 = &circle; shape1->draw();

    shape1 = &rectangle; shape1->draw();

    return 0;

}

```


---


**11b) Digital Library with Runtime Polymorphism**  

```cpp

#include <iostream>

#include <string>

using namespace std;


class Media {

protected:

    string title;

    bool isIssued;

public:

    Media(string t) : title(t), isIssued(false) {}

    virtual void addNewItem() = 0;

    virtual void issueItem() {

        if (isIssued) cout << "Item already issued" << endl;

        else { isIssued = true; cout << "Item Issued: " << title << endl; }

    }

    virtual void returnItem() {

        if (isIssued) { isIssued = false; cout << "Item Returned: " << title << endl; }

        else cout << "Item was not issued" << endl;

    }

};


class Book : public Media {

public:

    Book(string t) : Media(t) {}

    void addNewItem() override { cout << "Adding new Book: " << title << endl; }

    void issueItem() override { cout << "Issuing Book: "; Media::issueItem(); }

    void returnItem() override { cout << "Returning Book: "; Media::returnItem(); }

};


class Tape : public Media {

public:

    Tape(string t) : Media(t) {}

    void addNewItem() override { cout << "Adding new Tape: " << title << endl; }

    void issueItem() override { cout << "Issuing Tape: "; Media::issueItem(); }

    void returnItem() override { cout << "Returning Tape: "; Media::returnItem(); }

};


int main() {

    Media* media;

    Book book("C++ Programming");

    Tape tape("Jazz Music");

    media = &book; media->addNewItem(); media->issueItem(); media->returnItem();

    media = &tape; media->addNewItem(); media->issueItem(); media->returnItem();

    return 0;

}

```


---


**12a) String to Int and Vice Versa**  

```cpp

#include <iostream>

#include <string>

using namespace std;


int main() {

    string str = "12345";

    int num = stoi(str);

    cout << "String to int: " << num << endl;

    int newNum = 67890;

    string newStr = to_string(newNum);

    cout << "Int to string: " << newStr << endl;

    return 0;

}

```


---


**12b) Class ios Operations**  

```cpp

#include <iostream>

#include <iomanip>

using namespace std;


int main() {

    string str = "Hello";

    cout << setw(10) << setfill('*') << str << endl;

    cout.width(15); cout.fill('#');

    cout << str << endl;

    cout.setf(ios::showpos); cout << 123 << endl;

    cout.unsetf(ios::showpos); cout << 123 << endl;

    double number = 3.14159265358979323846;

    cout << "With precision 4: " << setprecision(4) << number << endl;

    cout << "With precision 6: " << setprecision(6) << number << endl;

    return 0;

}

```


---


**12c) I/O Operations on Characters**  

```cpp

#include <iostream>

#include <fstream>

#include <string>

#include <algorithm>

using namespace std;


int main() {

    string str1;

    cout << "Enter a string: "; getline(cin, str1);

    cout << "Length: " << str1.length() << endl;

    ofstream outputFile("output.txt");

    outputFile << str1; outputFile.close();

    ifstream inputFile("output.txt");

    string fetchedString; getline(inputFile, fetchedString);

    cout << "Fetched string: " << fetchedString << endl;

    return 0;

}

```


---


**13a) Copy File Contents**  

```cpp

#include <iostream>

#include <fstream>

#include <string>

using namespace std;


int main() {

    ifstream sourceFile("abc.txt");

    ofstream destinationFile("xyz.txt");

    string line;

    while (getline(sourceFile, line)) destinationFile << line << endl;

    sourceFile.close(); destinationFile.close();

    cout << "File copied successfully." << endl;

    return 0;

}

```


---


**13b) Binary I/O Operations**  

```cpp

#include <iostream>

#include <fstream>

using namespace std;


class Student {

public:

    string name;

    int age;

    Student(string n, int a) : name(n), age(a) {}

    void display() { cout << "Name: " << name << ", Age: " << age << endl; }

    void writeToFile(const string& filename) {

        ofstream outFile(filename);

        outFile << name << endl << age << endl;

        outFile.close();

    }

    void readFromFile(const string& filename) {

        ifstream inFile(filename);

        getline(inFile, name);

        inFile >> age;

        inFile.close();

    }

};


int main() {

    Student s1("Alice", 22);

    s1.writeToFile("student.txt");

    Student s2; s2.readFromFile("student.txt"); s2.display();

    return 0;

}

```


---


**14a) Multiple Catch Statements**  

```cpp

#include <iostream>

#include <stdexcept>

using namespace std;


int main() {

    try {

        int x = -1;

        throw out_of_range("Out of range error");

    }

    catch (const char* msg) { cout << "Caught C-string: " << msg << endl; }

    catch (const runtime_error& e) { cout << "Caught runtime_error: " << e.what() << endl; }

    catch (...) { cout << "Unknown exception" << endl; }

    return 0;

}

```


---


**14b) Rethrowing Exceptions**  

```cpp

#include <iostream>

#include <stdexcept>

using namespace std;


void testFunction() {

    try { throw runtime_error("Divide by zero error"); }

    catch (const runtime_error& e) { cout << "Caught: " << e.what(); throw; }

}


int main() {

    try { testFunction(); }

    catch (const runtime_error& e) { cout << "Rethrown: " << e.what() << endl; }

    return 0;

}

```


---


**15a) Class Template for Calculator**  

```cpp

#include <iostream>

using namespace std;


template <typename T>

class Calculator {

public:

    T add(T a, T b) { return a + b; }

    T subtract(T a, T b) { return a - b; }

    T multiply(T a, T b) { return a * b; }

    T divide(T a, T b) { return (b != 0) ? a / b : 0; }

};


int main() {

    Calculator<int> calcInt;

    cout << "Addition: " << calcInt.add(10, 5) << endl;

    Calculator<float> calcFloat;

    cout << "Division: " << calcFloat.divide(12.5f, 4.2f) << endl;

    return 0;

}

```


---


**15b) Template Function for Maximum**  

```cpp

#include <iostream>

using namespace std;


template <typename T>

T getMax(T a, T b) { return (a > b) ? a : b; }


int main() {

    cout << "Max (20 vs 10): " << getMax(20, 10) << endl;

    cout << "Max (12.5 vs 7.8): " << getMax(12.5f, 7.8f) << endl;

    return 0;

}

```




Post a Comment (0)
Previous Post Next Post