Exceptional Insights:C++ Files, Inheritance and Polymorphism

Discover the essence of C++ with practical insights into inheritance, polymorphism, file handling, and exception mastery. Elevate your coding skills effortlessly.

Exceptional Insights:C++ Files, Inheritance and Polymorphism

C++ Inheritance

Inheritance

Inheritance is one of the cornerstones of Object Oriented Programming (OOP). It allows us to create classes that inherit properties and methods from another class, known as its base class or parent class; any new class that inherits these characteristics from its base class becomes its derived class or sub-class. Inheritance reduces the amount of code needed to describe objects that share certain characteristics, and makes generic functions applicable across groups easier - for example predator() being called by all predator classes, canine() by all canines, claws() by all tigers having sharp claws! Additionally inheritance increases code reuse while simplifying program development efforts significantly.

With C++, it is possible to inherit methods and attributes in one program to the next. We classify "inheritance concept" into two categories:

  • Derived class (child) is the class that inherits from a different class
  • Base class (parent) The class is being inherited by

In order to inherit from classes utilize for inheritance, the : symbol.

In the case below in the example below, in the following example, Car class (child) takes on all the methods and attributes inherited from the Car class (parent):

Example

// Base class
class Vehicle {
  public:
    string brand = "Ford";
    void honk() {
      cout << "Tuut, tuut! \n" ;
    }
};

// Derived class
class Car: public Vehicle {
  public:
    string model = "Mustang";
};

int main() {
  Car myCar;
  myCar.honk();
  cout << myCar.brand + " " + myCar.model;
  return 0;
}

Why And When To Use "Inheritance"?

It's beneficial for code reuse: use the attributes and methods of classes that already exist when creating an entirely new class.

Types of Inheritance in c++

There are various forms of inheritance in c++, with Single Inheritance being the simplest type. Under Single Inheritance, an inheriting class inherits all public and protected data members of its parent class but cannot access private ones unless explicitly declared public in its child class. Multilevel or hierarchical inheritance can also occur.

Hierarchical inheritance allows a derived class to inherit from multiple classes at once, for instance the Electronic Device class inherits from both Computer and Linux-based classes simultaneously - this process is known as multilevel or multiple path inheritance.

Multiple inheritance is effective when there are classes with similar functions or data structures, such as students and employees who share similar responsibilities or data structures. For instance, Student and Employee classes could derive from the Person class which holds data such as name, date of birth, address and phone number; each of them could then specialize accordingly - Student for students while Employee is intended for employees.

Inheritance can also be used to implement polymorphism. The subclass ImaginaryNumber of Number has virtual methods which, when executed by objects of this class, invoke different implementations depending on their type at runtime.

One drawback of inheritance is its potential to create tight coupling between base and derived classes, leading to memory wastage and making modifications of base classes difficult if other derived classes depend on them.

As mentioned previously, inheritance should primarily be used to promote code reuse. As writing code manually can often be more efficient than creating new functions to complete similar tasks, inheritance should only be used sparingly and when absolutely necessary. Furthermore, before including them into your program it's a good practice to test all inherited functions; otherwise a bug in one base class could affect all its subclasses negatively - therefore including these into your unit tests (by adding them into a testing class) is another great way of making sure all functions work as intended!

C++ Multilevel Inheritance

Multilevel Inheritance

A class may also be created from one class that is created from another class.

As you can see in the next example MyGrandChild is derived form class MyChild (which is an extension of MyClass).

Example

// Base class (parent)
class MyClass {
  public:
    void myFunction() {
      cout << "Some content in parent class." ;
    }
};

// Derived class (child)
class MyChild: public MyClass {
};

// Derived class (grandchild)
class MyGrandChild: public MyChild {
};

int main() {
  MyGrandChild myObj;
  myObj.myFunction();
  return 0;
}

C++ Multiple Inheritance

Multiple Inheritance

A class could be created from multiple base class with the help of an separate list of commas:

Example

// Base class
class MyClass {
  public:
    void myFunction() {
      cout << "Some content in parent class." ;
    }
};

// Another base class
class MyOtherClass {
  public:
    void myOtherFunction() {
      cout << "Some content in another class." ;
    }
};

// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};

int main() {
  MyChildClass myObj;
  myObj.myFunction();
  myObj.myOtherFunction();
  return 0;
}

C++ Inheritance Access

Access Specifiers

It was explained in chapter 3 of the access Specifiers section that there exist three specifiers accessible within C++. So far, we've used only the two public (members of an class are accessible to anyone outside of in the course) as well as private (members are only accessible inside the course). The third type of specifier, protected, is identical to private however, it is also accessible through the inheritance class:

Example

// Base class
class Employee {
  protected: // Protected access specifier
    int salary;
};

// Derived class
class Programmer: public Employee {
  public:
    int bonus;
    void setSalary(int s) {
      salary = s;
    }
    int getSalary() {
      return salary;
    }
};

int main() {
  Programmer myObj;
  myObj.setSalary(50000);
  myObj.bonus = 15000;
  cout << "Salary: " << myObj.getSalary() << "\n";
  cout << "Bonus: " << myObj.bonus << "\n";
  return 0;
}

C++ Polymorphism

Polymorphism

Polymorphism is the term used to describe "many forms", and it is a sign of multiple classes that are linked to each other through inheritance.

As we mentioned in the above section, the inheritance method allows us to take on attributes and methods of an additional class. Polymorphism utilizes these methods to carry out various tasks. This lets us perform one action in multiple ways.

Consider, for instance, the base class Animal which has an option called AnimalSound(). Classes that derive from Animals could include Pigs, Cats, Dogs, Birds - And they also have their own version of a sound made by animals (the sound of a pig's oink, the cat meows. ):

Example

// Base class
class Animal {
  public:
    void animalSound() {
      cout << "The animal makes a sound \n";
    }
};

// Derived class
class Pig : public Animal {
  public:
    void animalSound() {
      cout << "The pig says: wee wee \n";
    }
};

// Derived class
class Dog : public Animal {
  public:
    void animalSound() {
      cout << "The dog says: bow wow \n";
    }
};

Keep in mind that in Chapter on Inheritance that we employ this : symbol to inherit from the class.

Now, we can make Dog or dog objects and then override our AnimalSound() method:

Example

// Base class
class Animal {
  public:
    void animalSound() {
      cout << "The animal makes a sound \n";
    }
};

// Derived class
class Pig : public Animal {
  public:
    void animalSound() {
      cout << "The pig says: wee wee \n";
    }
};

// Derived class
class Dog : public Animal {
  public:
    void animalSound() {
      cout << "The dog says: bow wow \n";
    }
};

int main() {
  Animal myAnimal;
  Pig myPig;
  Dog myDog;

  myAnimal.animalSound();
  myPig.animalSound();
  myDog.animalSound();
  return 0;
}

Why And When To Use "Inheritance" and "Polymorphism"?

It's beneficial for code reuse: Reuse attributes and methods from an already existing class whenever creating the new class.

C++ Files

C++ Files

The Fstream library lets us use files.

To use the Fstream library, which includes both the standard library and AND The Header file:

Example

#include 
#include 

The library has three classes in the library fstream. There are three classes in the library. They can be used to create files, read or write them:

Class Description
ofstream Writes and creates files
ifstream Reads files
Fstream A mixture of ifstream and ofstream: creates, reads and writes files

Create and Write To a File

To create a new file, employ or the ofstream or the fstream class. Then, specify what the title of your file.

If you want to write directly into the files, you can use the insert operation ( <<).

Example

#include 
#include 
using namespace std;

int main() {
  // Create and open a text file
  ofstream MyFile("filename.txt");

  // Write to the file
  MyFile << "Files can be tricky, but it is fun enough!";

  // Close the file
  MyFile.close();
}

Why should we shut down the file?

It's considered a good practice and helps clean out memory space that is not needed.

Read a File

To read a file, utilize either the Ifstream or the fstream class, along with what is the title of the file.

We also employ the when loop in conjunction with getline() function (which is part of the class ifstream class) to read the file line by line and to print the contents from the file.

Example

// Create a text string, which is used to output the text file
string myText;

// Read from the text file
ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
  // Output the text from the file
  cout << myText;
}

// Close the file
MyReadFile.close();

C++ Exceptions

C++ Exceptions

When you execute C++ code, various errors could occur. These include coding mistakes made by the programmers, errors due to input that is incorrect or any other unexpected factors.

If an error occurs, C++ will normally stop and create the error code. The technical meaning of the situation is C++ will throw an exception (throw an error).

C++ try and catch

The handling of exceptions handled in C++ consist of three key words: try, throw and catch:

Try statements are used to define a test. attempt statement lets you create a code block to be inspected for mistakes while it is executed.

Throw keyword keyword throw keyword triggers the exception when there is a fault is discovered, allowing us to make an error that is custom.

The catch statement lets you specify a block of code to be executed if there is a problem in this block.

It is believed that the attempt as well as catch words are grouped together:

Example

try {
  // Block of code to try
  throw exception; // Throw an exception when a problem arise
}
catch () {
  // Block of code to handle errors
}

Think about the following examples:

Example

try {
  int age = 15;
  if (age >= 18) {
    cout << "Access granted - you are old enough.";
  } else {
    throw (age);
  }
}
catch (int myNum) {
  cout << "Access denied - You must be at least 18 years old.\n";
  cout << "Age is: " << myNum;
}

Example explained

The try block is used to test a code If the age range is lower than 18, we'll throw an exception and deal with the situation in the catch block.

Within the block called the catch section, we detect the error and take action to fix the issue. The catch statement is based on an input parameter. In our case we will use the int type variable (myNum) (because we throw an exception for int type within this block (age)) and display the value of age.

If no error occurs (e.g. when the age exceeds 20, rather than 15 that is, it will be higher than 18) The capture blocks are skipped

Example

int age = 20;

It is also possible to use throw as a throw keyword to generate reference numbers, such as an individual error code or number to help organize your data:

Example

try {
  int age = 15;
  if (age >= 18) {
    cout << "Access granted - you are old enough.";
  } else {
    throw 505;
  }
}
catch (int myNum) {
  cout << "Access denied - You must be at least 18 years old.\n";
  cout << "Error number: " << myNum;
}

Handle Any Type of Exceptions (...)

If you don't know the throw type that is used within the attempt block you can utilize"three dots" syntax "three dots" syntax (...) in the catch block. It can handle any kind of error:

Example

try {
  int age = 15;
  if (age >= 18) {
    cout << "Access granted - you are old enough.";
  } else {
    throw 505;
  }
}
catch (...) {
  cout << "Access denied - You must be at least 18 years old.\n";
}

For more informative blogs, Please visit Home 

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow