Learning C++ Part 2 Example

C++ Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

Functions are used to perform certain actions, and they are important for reusing code: Define the code once, and use it many times.

Create a Function

C++ provides some pre-defined functions, such as main(), which is used to execute code. But you can also create your own functions to perform certain actions.

To create (often referred to as declare) a function, specify the name of the function, followed by parentheses ():

Syntax

  1. void myFunction() {
  2.   // code to be executed
  3. }

Example Explained

  • myFunction() is the name of the function
  • void means that the function does not have a return value. You will learn more about return values later in the next chapter
  • inside the function (the body), add code that defines what the function should do

Call a Function

Declared functions are not executed immediately. They are "saved for later use", and will be executed later, when they are called.

To call a function, write the function's name followed by two parentheses () and a semicolon ;

In the following example, myFunction() is used to print a text (the action), when it is called:

Example

Inside main, call myFunction():

  1. // Create a function
  2. void myFunction() {
  3.   cout << "I just got executed!";
  4. }

  5. int main() {
  6.   myFunction(); // call the function
  7.   return 0;
  8. }

  9. // Outputs "I just got executed!"

A function can be called multiple times:

Example

  1. void myFunction() {
  2.   cout << "I just got executed!\n";
  3. }

  4. int main() {
  5.   myFunction();
  6.   myFunction();
  7.   myFunction();
  8.   return 0;
  9. }

  10. // I just got executed!
  11. // I just got executed!
  12. // I just got executed!

Function Declaration and Definition

A C++ function consist of two parts:

  • Declaration: the return type, the name of the function, and parameters (if any)
  • Definition: the body of the function (code to be executed)

  1. void myFunction() { // declaration
  2.   // the body of the function (definition)
  3. }

Note: If a user-defined function, such as myFunction() is declared after the main() function, an error will occur:

Example

  1. int main() {
  2.   myFunction();
  3.   return 0;
  4. }

  5. void myFunction() {
  6.   cout << "I just got executed!";
  7. }

  8. // Error

However, it is possible to separate the declaration and the definition of the function - for code optimization.

You will often see C++ programs that have function declaration above main(), and function definition below main(). This will make the code better organized and easier to read:

Example

  1. // Function declaration
  2. void myFunction();

  3. // The main method
  4. int main() {
  5.   myFunction();  // call the function
  6.   return 0;
  7. }

  8. // Function definition
  9. void myFunction() {
  10.   cout << "I just got executed!";
  11. }

C++ Exercises

Test Yourself With Exercises

Exercise:

Create a function named myFunction and call it inside main().

  1. void _____ () {
  2.   cout << "I just got executed!";
  3. }

  4. int main() {  
  5.   __________ ;
  6.   return 0;
  7. }

Submit Answer »

Parameters and Arguments

Information can be passed to functions as a parameter. Parameters act as variables inside the function.

Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma:

Syntax

  1. void functionName(parameter1, parameter2, parameter3) {
  2.   // code to be executed
  3. }

The following example has a function that takes a string called fname as parameter. When the function is called, we pass along a first name, which is used inside the function to print the full name:

Example

  1. void myFunction(string fname) {
  2.   cout << fname << " Refsnes\n";
  3. }

  4. int main() {
  5.   myFunction("Liam");
  6.   myFunction("Jenny");
  7.   myFunction("Anja");
  8.   return 0;
  9. }

  10. // Liam Refsnes
  11. // Jenny Refsnes
  12. // Anja Refsnes

When a parameter is passed to the function, it is called an argument. So, from the example above: fname is a parameter, while Liam, Jenny and Anja are arguments.

Default Parameter Value

You can also use a default parameter value, by using the equals sign (=).

If we call the function without an argument, it uses the default value ("Norway"):

Example

  1. void myFunction(string country = "Norway") {
  2.   cout << country << "\n";
  3. }

  4. int main() {
  5.   myFunction("Sweden");
  6.   myFunction("India");
  7.   myFunction();
  8.   myFunction("USA");
  9.   return 0;
  10. }

  11. // Sweden
  12. // India
  13. // Norway
  14. // USA

A parameter with a default value, is often known as an "optional parameter". From the example above, country is an optional parameter and "Norway" is the default value.

Multiple Parameters

Inside the function, you can add as many parameters as you want:

Example

  1. void myFunction(string fname, int age) {
  2.   cout << fname << " Refsnes. " << age << " years old. \n";
  3. }

  4. int main() {
  5.   myFunction("Liam", 3);
  6. myFunction("Jenny", 14);
  7.   myFunction("Anja", 30);
  8.   return 0;
  9. }

  10. // Liam Refsnes. 3 years old.
  11. // Jenny Refsnes. 14 years old.
  12. // Anja Refsnes. 30 years old.

Note that when you are working with multiple parameters, the function call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.

Return Values

The void keyword, used in the previous examples, indicates that the function should not return a value. If you want the function to return a value, you can use a data type (such as int, string, etc.) instead of void, and use the return keyword inside the function:

Example

  1. int myFunction(int x) {
  2.   return 5 + x;
  3. }

  4. int main() {
  5.   cout << myFunction(3);
  6.   return 0;
  7. }

  8. // Outputs 8 (5 + 3)

This example returns the sum of a function with two parameters:

Example

  1. int myFunction(int x, int y) {
  2.   return x + y;
  3. }

  4. int main() {
  5.   cout << myFunction(5, 3);
  6.   return 0;
  7. }

  8. // Outputs 8 (5 + 3)

You can also store the result in a variable:

Example

  1. int myFunction(int x, int y) {
  2.   return x + y;
  3. }

  4. int main() {
  5.   int z = myFunction(5, 3);
  6.   cout << z;
  7.   return 0;
  8. }
  9. // Outputs 8 (5 + 3)

Pass By Reference

In the examples from the previous page, we used normal variables when we passed parameters to a function. You can also pass a reference to the function. This can be useful when you need to change the value of the arguments:

Example

  1. void swapNums(int &x, int &y) {
  2.   int z = x;
  3.   x = y;
  4.   y = z;
  5. }

  6. int main() {
  7.   int firstNum = 10;
  8.   int secondNum = 20;

  9.   cout << "Before swap: " << "\n";
  10.   cout << firstNum << secondNum << "\n";

  11.   // Call the function, which will change the values of firstNum and secondNum
  12.   swapNums(firstNum, secondNum);

  13.   cout << "After swap: " << "\n";
  14.   cout << firstNum << secondNum << "\n";

  15.   return 0;
  16. }

Pass Arrays as Function Parameters

You can also pass arrays to a function:

Example

  1. void myFunction(int myNumbers[5]) {
  2.   for (int i = 0; i < 5; i++) {
  3.     cout << myNumbers[i] << "\n";
  4.   }
  5. }

  6. int main() {
  7.   int myNumbers[5] = {10, 20, 30, 40, 50};
  8.   myFunction(myNumbers);
  9.   return 0;
  10. }

Example Explained

The function (myFunction) takes an array as its parameter (int myNumbers[5]), and loops through the array elements with the for loop.

When the function is called inside main(), we pass along the myNumbers array, which outputs the array elements.

Note that when you call the function, you only need to use the name of the array when passing it as an argument myFunction(myNumbers). However, the full declaration of the array is needed in the function parameter (int myNumbers[5]).

Function Overloading

With function overloading, multiple functions can have the same name with different parameters:

Example

  1. int myFunction(int x)
  2. float myFunction(float x)
  3. double myFunction(double x, double y)

Consider the following example, which have two functions that add numbers of different type:

Example

  1. int plusFuncInt(int x, int y) {
  2.   return x + y;
  3. }

  4. double plusFuncDouble(double x, double y) {
  5.   return x + y;
  6. }

  7. int main() {
  8.   int myNum1 = plusFuncInt(8, 5);
  9.   double myNum2 = plusFuncDouble(4.3, 6.26);
  10.   cout << "Int: " << myNum1 << "\n";
  11.   cout << "Double: " << myNum2;
  12.   return 0;
  13. }

Instead of defining two functions that should do the same thing, it is better to overload one.

In the example below, we overload the plusFunc function to work for both int and double:

Example

  1. int plusFunc(int x, int y) {
  2.   return x + y;
  3. }

  4. double plusFunc(double x, double y) {
  5.   return x + y;
  6. }

  7. int main() {
  8.   int myNum1 = plusFunc(8, 5);
  9.   double myNum2 = plusFunc(4.3, 6.26);
  10.   cout << "Int: " << myNum1 << "\n";
  11.   cout << "Double: " << myNum2;
  12.   return 0;
  13. }

Note: Multiple functions can have the same name as long as the number and/or type of parameters are different.

Recursion

Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.

Recursion Example

Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding two numbers:

Example

  1. int sum(int k) {
  2.   if (k > 0) {
  3.     return k + sum(k - 1);
  4.   } else {
  5.     return 0;
  6.   }
  7. }

  8. int main() {
  9.   int result = sum(10);
  10.   cout << result;
  11.   return 0;
  12. }

Example Explained

When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the result. When k becomes 0, the function just returns 0. When running, the program follows these steps:

  • 10 + sum(9)
  • 10 + ( 9 + sum(8) )
  • 10 + ( 9 + ( 8 + sum(7) ) )
  • ...
  • 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
  • 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

Since the function does not call itself when k is 0, the program stops there and returns the result.

The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.

C++ What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions.

Object-oriented programming has several advantages over procedural programming:

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time

Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the application, and place them at a single place and reuse them instead of repeating it.

C++ What are Classes and Objects?

Classes and objects are the two main aspects of object-oriented programming.

Look at the following illustration to see the difference between class and objects:

Class

Objects

Fruit

Apple

Banana

Mango

Another example:

Class

Objects

Car

Volvo

Audi

Toyota

So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the variables and functions from the class.

You will learn much more about classes and objects in the next chapter.

C++ Classes/Objects

C++ is an object-oriented programming language.

Everything in C++ is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

Attributes and methods are basically variables and functions that belongs to the class. These are often referred to as "class members".

A class is a user-defined data type that we can use in our program, and it works as an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the class keyword:

Example

Create a class called "MyClass":

  1. class MyClass {       // The class
  2.   public:             // Access specifier
  3.     int myNum;        // Attribute (int variable)
  4.     string myString;  // Attribute (string variable)
  5. };

Example explained

  • The class keyword is used to create a class called MyClass.
  • The public keyword is an access specifier, which specifies that members (attributes and methods) of the class are accessible from outside the class. You will learn more about access specifiers later.
  • Inside the class, there is an integer variable myNum and a string variable myString. When variables are declared within a class, they are called attributes.
  • At last, end the class definition with a semicolon;.

Create an Object

In C++, an object is created from a class. We have already created the class named MyClass, so now we can use this to create objects.

To create an object of MyClass, specify the class name, followed by the object name.

To access the class attributes (myNum and myString), use the dot syntax (.) on the object:

Example

Create an object called "myObj" and access the attributes:

  1. class MyClass {       // The class
  2.   public:             // Access specifier
  3.     int myNum;        // Attribute (int variable)
  4.     string myString;  // Attribute (string variable)
  5. };

  6. int main() {
  7.   MyClass myObj;  // Create an object of MyClass

  8.   // Access attributes and set values
  9.   myObj.myNum = 15; 
  10.   myObj.myString = "Some text";

  11.   // Print attribute values
  12.   cout << myObj.myNum << "\n";
  13.   cout << myObj.myString;
  14.   return 0;
  15. }

Multiple Objects

You can create multiple objects of one class:

Example

  1. // Create a Car class with some attributes
  2. class Car {
  3.   public:
  4.     string brand;   
  5.     string model;
  6.     int year;
  7. };

  8. int main() {
  9.   // Create an object of Car
  10.   Car carObj1;
  11.   carObj1.brand = "BMW";
  12.   carObj1.model = "X5";
  13.   carObj1.year = 1999;

  14.   // Create another object of Car
  15.   Car carObj2;
  16.   carObj2.brand = "Ford";
  17.   carObj2.model = "Mustang";
  18.   carObj2.year = 1969;

  19.   // Print attribute values
  20.   cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  21.   cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  22.   return 0;
  23. }

C++ Exercises

Test Yourself With Exercises

Exercise:

Create an object of MyClass called myObj.

  1. __________ ________ ;

Submit Answer »

Class Methods

Methods are functions that belongs to the class.

There are two ways to define functions that belongs to a class:

  • Inside class definition
  • Outside class definition

In the following example, we define a function inside the class, and we name it "myMethod".

Note: You access methods just like you access attributes; by creating an object of the class and using the dot syntax (.):

Inside Example

  1. class MyClass {        // The class
  2.   public:              // Access specifier
  3.     void myMethod() {  // Method/function defined inside the class
  4.       cout << "Hello World!";
  5.     }
  6. };

  7. int main() {
  8.   MyClass myObj;     // Create an object of MyClass
  9.   myObj.myMethod();  // Call the method
  10.   return 0;
  11. }

To define a function outside the class definition, you have to declare it inside the class and then define it outside of the class. This is done by specifiying the name of the class, followed the scope resolution :: operator, followed by the name of the function:

Outside Example

  1. class MyClass {        // The class
  2.   public:              // Access specifier
  3.     void myMethod();   // Method/function declaration
  4. };

  5. // Method/function definition outside the class
  6. void MyClass::myMethod() {
  7.   cout << "Hello World!";
  8. }

  9. int main() {
  10.   MyClass myObj;     // Create an object of MyClass
  11.   myObj.myMethod();  // Call the method
  12.   return 0;
  13. }

Parameters

You can also add parameters:

Example

  1. #include <iostream>
  2. using namespace std;

  3. class Car {
  4.   public:
  5.     int speed(int maxSpeed);
  6. };

  7. int Car::speed(int maxSpeed) {
  8.   return maxSpeed;
  9. }

  10. int main() {
  11.   Car myObj; // Create an object of Car
  12.   cout << myObj.speed(200); // Call the method with an argument
  13.   return 0;
  14. }

Constructors

A constructor in C++ is a special method that is automatically called when an object of a class is created.

To create a constructor, use the same name as the class, followed by parentheses ():

Example

  1. class MyClass {     // The class
  2.   public:           // Access specifier
  3.     MyClass() {     // Constructor
  4.       cout << "Hello World!";
  5.     }
  6. };

  7. int main() {
  8.   MyClass myObj;    // Create an object of MyClass (this will call the constructor)
  9.   return 0;
  10. }

Note: The constructor has the same name as the class, it is always public, and it does not have any return value.

Constructor Parameters

Constructors can also take parameters (just like regular functions), which can be useful for setting initial values for attributes.

The following class have brand, model and year attributes, and a constructor with different parameters. Inside the constructor we set the attributes equal to the constructor parameters (brand=x, etc). When we call the constructor (by creating an object of the class), we pass parameters to the constructor, which will set the value of the corresponding attributes to the same:

Example

  1. class Car {        // The class
  2.   public:          // Access specifier
  3.     string brand;  // Attribute
  4.     string model;  // Attribute
  5.     int year;      // Attribute
  6.     Car(string x, string y, int z) { // Constructor with parameters
  7.       brand = x;
  8.       model = y;
  9.       year = z;
  10.     }
  11. };

  12. int main() {
  13.   // Create Car objects and call the constructor with different values
  14.   Car carObj1("BMW", "X5", 1999);
  15.   Car carObj2("Ford", "Mustang", 1969);

  16.   // Print values
  17.   cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  18.   cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  19.   return 0;
  20. }

Just like functions, constructors can also be defined outside the class. First, declare the constructor inside the class, and then define it outside of the class by specifying the name of the class, followed by the scope resolution :: operator, followed by the name of the constructor (which is the same as the class):

Example

  1. class Car {        // The class
  2.   public:          // Access specifier
  3.     string brand;  // Attribute
  4.     string model;  // Attribute
  5.     int year;      // Attribute
  6.     Car(string x, string y, int z); // Constructor declaration
  7. };

  8. // Constructor definition outside the class
  9. Car::Car(string x, string y, int z) {
  10.   brand = x;
  11.   model = y;
  12.   year = z;
  13. }

  14. int main() {
  15.   // Create Car objects and call the constructor with different values
  16.   Car carObj1("BMW", "X5", 1999);
  17.   Car carObj2("Ford", "Mustang", 1969);

  18.   // Print values
  19.   cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  20.   cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  21.   return 0;
  22. }

Access Specifiers

By now, you are quite familiar with the public keyword that appears in all of our class examples:

Example

  1. class MyClass {  // The class
  2.   public:        // Access specifier
  3.     // class members goes here
  4. };

The public keyword is an access specifier. Access specifiers define how the members (attributes and methods) of a class can be accessed. In the example above, the members are public - which means that they can be accessed and modified from outside the code.

However, what if we want members to be private and hidden from the outside world?

In C++, there are three access specifiers:

  • public - members are accessible from outside the class
  • private - members cannot be accessed (or viewed) from outside the class
  • protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes. You will learn more about Inheritance later.

In the following example, we demonstrate the differences between public and private members:

Example

  1. class MyClass {
  2.   public:    // Public access specifier
  3.     int x;   // Public attribute
  4.   private:   // Private access specifier
  5.     int y;   // Private attribute
  6. };

  7. int main() {
  8.   MyClass myObj;
  9.   myObj.x = 25;  // Allowed (public)
  10.   myObj.y = 50;  // Not allowed (private)
  11.   return 0;
  12. }

If you try to access a private member, an error occurs:

  • error: y is private

Note: It is possible to access private members of a class using a public method inside the same class. See the next chapter (Encapsulation) on how to do this.

Tip: It is considered good practice to declare your class attributes as private (as often as you can). This will reduce the possibility of yourself (or others) to mess up the code. This is also the main ingredient of the Encapsulation concept, which you will learn more about in the next chapter.

Note: By default, all members of a class are private if you don't specify an access specifier:

Example

  1. class MyClass {
  2.   int x;   // Private attribute
  3.   int y;   // Private attribute
  4. };

Encapsulation

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide public get and set methods.

Access Private Members

To access a private attribute, use public "get" and "set" methods:

Example

  1. #include <iostream>
  2. using namespace std;

  3. class Employee {
  4.   private:
  5.     // Private attribute
  6.     int salary;

  7.   public:
  8.     // Setter
  9.     void setSalary(int s) {
  10.       salary = s;
  11.     }
  12.     // Getter
  13.     int getSalary() {
  14.       return salary;
  15.     }
  16. };

  17. int main() {
  18.   Employee myObj;
  19.   myObj.setSalary(50000);
  20.   cout << myObj.getSalary();
  21.   return 0;
  22. }

Example explained

The salary attribute is private, which have restricted access.

The public setSalary() method takes a parameter (s) and assigns it to the salary attribute (salary = s).

The public getSalary() method returns the value of the private salary attribute.

Inside main(), we create an object of the Employee class. Now we can use the setSalary() method to set the value of the private attribute to 50000. Then we call the getSalary() method on the object to return the value.

Why Encapsulation?

  • It is considered good practice to declare your class attributes as private (as often as you can). Encapsulation ensures better control of your data, because you (or others) can change one part of the code without affecting other parts
  • Increased security of data

Inheritance

In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:

  • derived class (child) - the class that inherits from another class
  • base class (parent) - the class being inherited from

To inherit from a class, use the: symbol.

In the example below, the Car class (child) inherits the attributes and methods from the Vehicle class (parent):

Example

  1. // Base class
  2. class Vehicle {
  3.   public:
  4.     string brand = "Ford";
  5.     void honk() {
  6.       cout << "Tuut, tuut! \n" ;
  7.     }
  8. };

  9. // Derived class
  10. class Car: public Vehicle {
  11.   public:
  12.     string model = "Mustang";
  13. };

  14. int main() {
  15.   Car myCar;
  16.   myCar.honk();
  17.   cout << myCar.brand + " " + myCar.model;
  18.   return 0;
  19. }

Why And When To Use "Inheritance"?

- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

Multilevel Inheritance

A class can also be derived from one class, which is already derived from another class.

In the following example, MyGrandChild is derived from class MyChild (which is derived from MyClass).

Example

  1. // Base class (parent)
  2. class MyClass {
  3.   public:
  4.     void myFunction() {
  5.       cout << "Some content in parent class." ;

  6.     }
  7. };

  8. // Derived class (child)
  9. class MyChild: public MyClass {
  10. };

  11. // Derived class (grandchild)
  12. class MyGrandChild: public MyChild {
  13. };

  14. int main() {
  15.   MyGrandChild myObj;
  16.   myObj.myFunction();
  17.   return 0;
  18. }

Multiple Inheritance

A class can also be derived from more than one base class, using a comma-separated list:

Example

  1. // Base class
  2. class MyClass {
  3.   public:
  4.     void myFunction() {
  5.       cout << "Some content in parent class." ;
  6.     }
  7. };

  8. // Another base class
  9. class MyOtherClass {
  10.   public:
  11.     void myOtherFunction() {
  12.       cout << "Some content in another class." ;
  13.     }
  14. };

  15. // Derived class
  16. class MyChildClass: public MyClass, public MyOtherClass {
  17. };

  18. int main() {
  19.   MyChildClass myObj;
  20.   myObj.myFunction();
  21.   myObj.myOtherFunction();
  22.   return 0;
  23. }

Access Specifiers

You learned from the Access Specifiers chapter that there are three specifiers available in C++. Until now, we have only used public (members of a class are accessible from outside the class) and private (members can only be accessed within the class). The third specifier, protected, is similar to private, but it can also be accessed in the inherited class:

Example

  1. // Base class
  2. class Employee {
  3.   protected: // Protected access specifier
  4.     int salary;
  5. };

  6. // Derived class
  7. class Programmer: public Employee {
  8.   public:
  9.     int bonus;
  10.     void setSalary(int s) {
  11.       salary = s;
  12.     }
  13.     int getSalary() {
  14.       return salary;
  15.     }
  16. };

  17. int main() {
  18.   Programmer myObj;
  19.   myObj.setSalary(50000);
  20.   myObj.bonus = 15000;
  21.   cout << "Salary: " << myObj.getSalary() << "\n";
  22.   cout << "Bonus: " << myObj.bonus << "\n";
  23.   return 0;
  24. }

Polymorphism

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.

Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

For example, think of a base class called Animal that has a method called animalSound(). Derived classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):

Example

  1. // Base class
  2. class Animal {
  3.   public:
  4.     void animalSound() {
  5.       cout << "The animal makes a sound \n";
  6.     }
  7. };

  8. // Derived class
  9. class Pig : public Animal {
  10.   public:
  11.     void animalSound() {
  12.       cout << "The pig says: wee wee \n";
  13.     }
  14. };

  15. // Derived class
  16. class Dog : public Animal {
  17.   public:
  18.     void animalSound() {
  19.       cout << "The dog says: bow wow \n";
  20.     }
  21. };

Remember from the Inheritance chapter that we use the : symbol to inherit from a class.

Now we can create Pig and Dog objects and override the animalSound() method:

Example

  1. // Base class
  2. class Animal {
  3.   public:
  4.     void animalSound() {
  5.       cout << "The animal makes a sound \n";
  6.     }
  7. };

  8. // Derived class
  9. class Pig : public Animal {
  10.   public:
  11.     void animalSound() {
  12.       cout << "The pig says: wee wee \n";
  13.     }
  14. };

  15. // Derived class
  16. class Dog : public Animal {
  17.   public:
  18.     void animalSound() {
  19.       cout << "The dog says: bow wow \n";
  20.     }
  21. };

  22. int main() {
  23.   Animal myAnimal;
  24.   Pig myPig;
  25.   Dog myDog;

  26.   myAnimal.animalSound();
  27.   myPig.animalSound();
  28.   myDog.animalSound();
  29.   return 0;
  30. }

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

- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

C++ Files

The fstream library allows us to work with files.

To use the fstream library, include both the standard <iostream> AND the <fstream> header file:

Example

  1. #include <iostream>
  2. #include <fstream>

There are three classes included in the fstream library, which are used to create, write or read files:

Class

Description

ofstream

Creates and writes to files

ifstream

Reads from files

fstream

A combination of ofstream and ifstream: creates, reads, and writes to files

Create and Write To a File

To create a file, use either the ofstream or fstream class, and specify the name of the file.

To write to the file, use the insertion operator (<<).

Example

  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;

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

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

  9.   // Close the file
  10.   MyFile.close();
  11. }

Why do we close the file?

It is considered good practice, and it can clean up unnecessary memory space.

Read a File

To read from a file, use either the ifstream or fstream class, and the name of the file.

Note that we also use a while loop together with the getline() function (which belongs to the  ifstream class) to read the file line by line, and to print the content of the file:

Example

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

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

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

  10. // Close the file
  11. MyReadFile.close();

C++ Exceptions

When executing C++ code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, C++ will normally stop and generate an error message. The technical term for this is: C++ will throw an exception (throw an error).

C++ try and catch

Exception handling in C++ consist of three keywords: try, throw and catch:

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The throw keyword throws an exception when a problem is detected, which lets us create a custom error.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

Example

  1. try {
  2.   // Block of code to try
  3.   throw exception; // Throw an exception when a problem arise
  4. }
  5. catch () {
  6.   // Block of code to handle errors
  7. }

Consider the following example:

Example

  1. try {
  2.   int age = 15;
  3.   if (age >= 18) {
  4.     cout << "Access granted - you are old enough.";
  5.   } else {
  6.     throw (age);
  7.   }
  8. }
  9. catch (int myNum) {
  10.   cout << "Access denied - You must be at least 18 years old.\n";
  11.   cout << "Age is: " << myNum;
  12. }

Example explained

We use the try block to test some code: If the age variable is less than 18, we will throw an exception, and handle it in our catch block.

In the catch block, we catch the error and do something about it. The catch statement takes a parameter: in our example we use an int variable (myNum) (because we are throwing an exception of int type in the try block (age)), to output the value of age.

If no error occurs (e.g. if age is 20 instead of 15, meaning it will be be greater than 18), the catch block is skipped:

Example

  1. int age = 20;

You can also use the throw keyword to output a reference number, like a custom error number/code for organizing purposes:

Example

  1. try {
  2.   int age = 15;
  3.   if (age >= 18) {
  4.     cout << "Access granted - you are old enough.";
  5.   } else {
  6.     throw 505;
  7.   }
  8. }
  9. catch (int myNum) {
  10.   cout << "Access denied - You must be at least 18 years old.\n";
  11.   cout << "Error number: " << myNum;
  12. }

Handle Any Type of Exceptions (...)

If you do not know the throw type used in the try block, you can use the "three dots" syntax (...) inside the catch block, which will handle any type of exception:

Example

  1. try {
  2.   int age = 15;
  3.   if (age >= 18) {
  4.     cout << "Access granted - you are old enough.";
  5.   } else {
  6.     throw 505;
  7.   }
  8. }
  9. catch (...) {
  10.   cout << "Access denied - You must be at least 18 years old.\n";
  11. }

C++ How To Add Two Numbers
Add Two Numbers

Learn how to add two numbers in C++:

Example

  1. int x = 5;
  2. int y = 6;
  3. int sum = x + y;
  4. cout << sum;

Add Two Numbers with User Input

In this example, the user must input two numbers. Then we print the sum by calculating (adding) the two numbers:

Example

  1. int x, y;
  2. int sum;
  3. cout << "Type a number: ";
  4. cin >> x;
  5. cout << "Type another number: ";
  6. cin >> y;
  7. sum = x + y;
  8. cout << "Sum is: " << sum;

Comments