- Computer Science Lecturer Test Preparation (Part-2)
- How while loop works?
- How do…while loop works?
- Passing Multidimensional Array to a Function
- Passing String to a Function
- Reference operator (&) and Deference operator (*)
- The new Operator
- The delete Operator
- Keywords: private and public
- C++ Objects
- How to access data member and member function in C++?
- C++ Constructors
- Constructor Overloading
- How to pass and return object from a function in C++?
- How to return an object from the function?
- C++ Operator Overloading
- Things to remember
- Following best practices while using operator overloading
- C++ Inheritance
- Why inheritance should be used?
- Access specifiers in Inheritance
- Member Function Overriding in Inheritance
- C++ Function Overriding
- How to access the overridden function in the base class from the derived class?
- C++ Multiple, Multilevel and Hierarchical Inheritance
- Ambiguity in Multiple Inheritance
- C++ Hierarchical Inheritance
- C++ friend Function and friend Classes
- friend Function in C++
- C++ Virtual Function
- C++ Templates
- Function Templates
- How to declare a function template?
- How to create a class template object?
Computer Science Lecturer Test Preparation (Part-2)
Computer Science Lecturer Test Preparation Part-1 Computer Science Lecturer Test Preparation Part-2 Computer Science Lecturer Test Preparation Part-3 Computer Science Lecturer Test Preparation Part-4
How for loop works?
- The initialization statement is executed only once at the beginning.
- Then, the test expression is evaluated.
- If the test expression is false, for loop is terminated. But if the test expression is true, codes inside body of for loop is executed and update expression is updated.
- Again, the test expression is evaluated and this process repeats until the test expression is false.
How while loop works?
- The while loop evaluates the test expression.
- If the test expression is true, codes inside the body of while loop is evaluated.
- Then, the test expression is evaluated again. This process goes on until the test expression is false.
- When the test expression is false, while loop is terminated.
- C++ do…while Loop
- The do…while loop is a variant of the while loop with one important difference. The body of do…while loop is executed once before the test expression is checked.
How do…while loop works?
- The codes inside the body of loop is executed at least once. Then, only the test expression is checked.
- If the test expression is true, the body of loop is executed. This process continues until the test expression becomes false.
- When the test expression is false, do…while loop is terminated.
C++ break and continue Statement
n C++, there are two statements break; and continue; specifically to alter the normal flow of a program.
Sometimes, it is desirable to skip the execution of a loop for a certain test condition or terminate it immediately without checking the condition.
For example: You want to loop through data of all aged people except people aged 65. Or, you want to find the first person aged 20.
In scenarios like these, continue; or a break; statement is used.
C++ break Statement
The break; statement terminates a loop (for, while and do..while loop) and a switch statement immediately when it appears.
Multidimensional Array Initialization
You can initialize a multidimensional array in more than one way.
As the number of dimension increases, the complexity also increases tremendously although the concept is quite similar.
Arrays can be passed to a function as an argument. Consider this example to pass one-dimensional array to a function:
When an array is passed as an argument to a function, only the name of an array is used as argument.
Also notice the difference while passing array as an argument rather than a variable.
void display(int m);
Passing Multidimensional Array to a Function
Multidimensional array can be passed in similar way as one-dimensional array
Note: Multidimensional array with dimension more than 2 can be passed in similar way as two dimensional array.
In C programming, the collection of characters is stored in the form of arrays, this is also supported in C++ programming. Hence it’s called C-strings.
C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value of null character is 0).
In C++, you can also create a string object for holding strings.
Unlike using char arrays, string objects has no fixed length, and can be extended as per your requirement.
Passing String to a Function
Strings are passed to a function in a similar way arrays are passed to a function.
Pointers are powerful features of C++ that differentiates it from other programming languages like Java and Python.
Pointers are used in C++ program to access the memory and manipulate the address.
Address in C++
To understand pointers, you should first know how data is stored on the computer.
Each variable you create in your program is assigned a location in the computer’s memory. The value the variable stores is actually stored in the location assigned.
To know where the data is stored, C++ has an & operator. The & (reference) operator gives you the address occupied by a variable.
If var is a variable then, &var gives the address of that variable.
C++ gives you the power to manipulate the data in the computer’s memory directly. You can assign and de-assign any space in the memory as you wish. This is done using Pointer variables.
Pointers variables are variables that points to a specific address in the memory pointed by another variable.
Reference operator (&) and Deference operator (*)
Reference operator (&) as discussed above gives the address of a variable.
To get the value stored in the memory address, we use the dereference operator (*).
For example: If a number variable is stored in the memory address 0x123, and it contains a value 5.
The reference (&) operator gives the value 0x123, while the dereference (*) operator gives the value 5.
Note: The (*) sign used in the declaration of C++ pointer is not the dereference pointer. It is just a similar notation that creates a pointer.
Pointers are the variables that hold address. Not only can pointers store address of a single variable, it can also store address of cells of an array.
In C++ Functions article, you learned about passing arguments to a function. This method used is called passing by value because the actual value is passed.
However, there is another way of passing an argument to a function where where the actual value of the argument is not passed. Instead, only the reference to that value is passed.
Arrays can be used to store multiple homogenous data but there are serious drawbacks of using arrays.
You should allocate the memory of an array when you declare it but most of the time, the exact memory needed cannot be determined until runtime.
The best thing to do in this situation is to declare an array with maximum possible memory required (declare array with maximum possible size expected).
The downside to this is unused memory is wasted and cannot be used by any other programs.
To avoid wastage of memory, you can dynamically allocate memory required during runtime using new and delete operator in C++.
The new Operator
ptr = new float[num];
This expression in the above program returns a pointer to a section of memory just large enough to hold the num number of floating-point data.
The delete Operator
Once the memory is allocated using new operator, it should released back to the operating system.
If the program uses a large amount of memory using new, system may crash because there will be no memory available for the operating system.
The following expression returns memory back to the operating system.
delete  ptr;
The brackets  indicates the array has been deleted. If you need to delete a single object then, you don’t need to use brackets.
C++ is a multi-paradigm programming language. Meaning, it supports different programming styles.
One of the popular ways to solve a programming problem is by creating objects, known as object-oriented style of programming.
C++ supports object-oriented (OO) style of programming which allows you to divide complex problems into smaller sets by creating objects.
Object is simply a collection of data and functions that act on those data.
Before you create an object in C++, you need to define a class.
A class is a blueprint for the object.
We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.
As, many houses can be made from the same description, we can create many objects from a class.
Keywords: private and public
You may have noticed two keywords: private and public in the above example.
The private keyword makes data and functions private. Private data and functions can be accessed only from inside the same class.
The public keyword makes data and functions public. Public data and functions can be accessed out of the class.
Here, data1 and data2 are private members where as function1() and function2() are public members.
If you try to access private data from outside of the class, compiler throws error. This feature in OOP is known as data hiding.
When class is defined, only the specification for the object is defined; no memory or storage is allocated.
To use the data and access functions defined in the class, you need to create objects.
How to access data member and member function in C++?
You can access the data members and member functions by using a . (dot) operator. For example,
This will call the function1() function inside the Test class for objects o2.
Similarly, the data member can be accessed as:
o1.data2 = 5.5;
It is important to note that, the private members can be accessed only from inside the class.
So, you can use o2.function1(); from any function or class in the above example. However, the code o1.data2 = 5.5; should always be inside the class Test.
onstructors are special type of member functions that initialises an object automatically when it is created.
Compiler identifies a given member function is a constructor or not by its name and the return type.
Constructor has the same name as that of the class and it does not have any return type. Also, the constructor is always be public.
How constructor works?
In the above pseudo code, temporary() is a constructor.
When an object of class temporary is created, the constructor is called automatically, and xis initialized to 5 and y is initialized to 5.5.
You can also initialise the data members inside the constructor’s body as below. However, this method is not preferred.
x = 5;
y = 5.5;
// This method is not preferred.
Use of Constructor in C++
Suppose you are working on 100’s of Person objects and the default value of a data member age is 0. Initialising all objects manually will be a very tedious task.
Instead, you can define a constructor that initialises age to 0. Then, all you have to do is create a Person object and the constructor will automatically initialise the age.
These situations arise frequently while handling array of objects.
Also, if you want to execute some code immediately after an object is created, you can place the code inside the body of the constructor.
Constructor can be overloaded in a similar way as function overloading.
Overloaded constructors have the same name (name of the class) but different number of arguments.
Depending upon the number and type of arguments passed, specific constructor is called.
Since, there are multiple constructors present, argument to the constructor should also be passed while creating an object.
Default Copy Constructor
An object can be initialized with another object of same type. This is same as copying the contents of a class to another class.
How to pass and return object from a function in C++?
In C++ programming, objects can be passed to a function in a similar way as structures.
How to return an object from the function?
In C++ programming, object can be returned from a function in a similar way as structures.
C++ Operator Overloading
The meaning of an operator is always same for variable of basic types like: int, float, double etc. For example: To add two integers, + operator is used.
However, for user-defined types (like: objects), you can redefine the way operator works. For example:
If there are two objects of a class that contains string as its data members. You can redefine the meaning of + operator and use it to concatenate those strings.
This feature in C++ programming that allows programmer to redefine the meaning of an operator (when they operate on class objects) is known as operator overloading.
Why is operator overloading used?
You can write any C++ program without the knowledge of operator overloading. However, operator operating are profoundly used by programmers to make program intuitive.
Things to remember
- Operator overloading allows you to redefine the way operator works for user-defined types only (objects, structures). It cannot be used for built-in types (int, float, char etc.).
- Two operators = and & are already overloaded by default in C++. For example: To copy objects of same class, you can directly use = operator. You do not need to create an operator function.
- Operator overloading cannot change the precedence and associatively of operators. However, if you want to change the order of evaluation, parenthesis should be used.
- There are 4 operators that cannot be overloaded in C++. They are :: (scope resolution), . (member selection), .* (member selection through pointer to function) and ?:(ternary operator).
Following best practices while using operator overloading
Operator overloading allows you to define the way operator works
nheritance is one of the key features of Object-oriented programming in C++. It allows user to create a new class (derived class) from an existing class(base class).
The derived class inherits all the features from the base class and can have additional features of its own.
Why inheritance should be used?
Suppose, in your game, you want three characters – a maths teacher, a footballer and a businessman.
Since, all of the characters are persons, they can walk and talk. However, they also have some special skills. A maths teacher can teach maths, a footballer can play football and a businessman can run a business.
You can individually create three classes who can walk, talk and perform their special skill as shown in the figure below.
In each of the classes, you would be copying the same code for walk and talk for each character.
If you want to add a new feature – eat, you need to implement the same code for each character. This can easily become error prone (when copying) and duplicate codes.
It’d be a lot easier if we had a Person class with basic features like talk, walk, eat, sleep, and add special skills to those features as per our characters. This is done using inheritance.
Using inheritance, now you don’t implement the same code for walk and talk for each class. You just need to inherit them.
So, for Maths teacher (derived class), you inherit all features of a Person (base class) and add a new feature TeachMaths. Likewise, for a footballer, you inherit all the features of a Person and add a new feature PlayFootball and so on.
This makes your code cleaner, understandable and extendable.
It is important to remember: When working with inheritance, each derived class should satisfy the condition whether it “is a” base class or not. In the example above, Maths teacher is a Person, Footballer is a Person. You cannot have: Businessman is a Business.
Access specifiers in Inheritance
When creating a derived class from a base class, you can use different access specifiers to inherit the data members of the base class.
These can be public, protected or private.
In the above example, the base class Person has been inherited public-ly by MathsTeacherand Footballer.
Member Function Overriding in Inheritance
Suppose, base class and derived class have member functions with same name and arguments.
If you create an object of the derived class and try to access that member function, the member function in derived class is only invoked.
The member function of derived class overrides the member function of base class.
C++ Function Overriding
Inheritance allows software developers to derive a new class from the existing class. The derived class inherits features of the base class (existing class).
Suppose, both base class and derived class have a member function with same name and arguments (number and type of arguments).
If you create an object of the derived class and call the member function which exists in both classes (base and derived), the member function of the derived class is invoked and the function of the base class is ignored.
This feature in C++ is known as function overriding.
How to access the overridden function in the base class from the derived class?
To access the overridden function of the base class from the derived class, scope resolution operator :: is used.
C++ Multiple, Multilevel and Hierarchical Inheritance
Inheritance is one of the core feature of an object-oriented programming language. It allows software developers to derive a new class from the existing class. The derived class inherits the features of the base class (existing class).
C++ Multiple Inheritance
In C++ programming, a class can be derived from more than one parents. For example: A class Bat is derived from base classes Mammal and WingedAnimal. It makes sense because bat is a mammal as well as a winged animal.
Ambiguity in Multiple Inheritance
The most obvious problem with multiple inheritance occurs during function overriding.
Suppose, two base classes have a same function which is not overridden in derived class.
If you try to call the function using the object of the derived class, compiler shows error. It’s because compiler doesn’t know which function to call
C++ Hierarchical Inheritance
If more than one class is inherited from the base class, it’s known as hierarchical inheritance. In hierarchical inheritance, all features that are common in child classes are included in the base class.
C++ friend Function and friend Classes
One of the important concepts of OOP is data hiding, i.e., a nonmember function cannot access an object’s private or protected data.
But, sometimes this restriction may force programmer to write long and complex codes. So, there is mechanism built in C++ programming to access private or protected data from non-member functions.
This is done using a friend function or/and a friend class.
friend Function in C++
If a function is defined as a friend function then, the private and protected data of a class can be accessed using the function.
The complier knows a given function is a friend function by the use of the keyword friend.
For accessing the data, the declaration of a friend function should be made inside the body of the class (can be anywhere inside class either in private or public section) starting with keyword friend.
C++ Virtual Function
A virtual function is a member function in base class that you expect to redefine in derived classes.
Before going into detail, let’s build an intuition on why virtual functions are needed in the first place.
C++ Abstract class and Pure virtual Function
The goal of object-oriented programming is to divide a complex problem into small sets. This helps understand and work with problem in an efficient way.
Sometimes, it’s desirable to use inheritance just for the case of better visualization of the problem.
In C++, you can create an abstract class that cannot be instantiated (you cannot create object of that class). However, you can derive a class from it and instantiate object of the derived class.
Abstract classes are the base class which cannot be instantiated.
A class containing pure virtual function is known as abstract class.
Pure Virtual Function
A virtual function whose declaration ends with =0 is called a pure virtual function.
Templates are powerful features of C++ which allows you to write generic programs. In simple terms, you can create a single function or a class to work with different data types using templates.
Templates are often used in larger codebase for the purpose of code reusability and flexibility of the programs.
The concept of templates can be used in two different ways:
- Function Templates
- Class Templates
A function template works in a similar to a normal function, with one key difference.
A single function template can work with different data types at once but, a single normal function can only work with one set of data types.
Normally, if you need to perform identical operations on two or more types of data, you use function overloading to create two functions with the required function declaration.
However, a better approach would be to use function templates because you can perform the same task writing less and maintainable code.
How to declare a function template?
A function template starts with the keyword template followed by template parameter/s inside < > which is followed by function declaration.
Like function templates, you can also create class templates for generic class operations.
Sometimes, you need a class implementation that is same for all classes, only the data types used are different.
Normally, you would need to create a different class for each data type OR create different member variables and functions within a single class.
This will unnecessarily bloat your code base and will be hard to maintain, as a change is one class/function should be performed on all classes/functions.
However, class templates make it easy to reuse the same code for all data types.
How to create a class template object?
To create a class template object, you need to define the data type inside a < > when creation.