News

An Overview of C++: Learn About Polymorphism, Constructors & more

An Overview of C++ Learn About Polymorphism, Constructors & more

C++, the first or second programming language for most school students to get acquainted with, is a popular general-purpose language. Even though it is an old programming language, it remains the core of several important applications and a potential alternative for developing operating systems, games, web browsers, etc. If you ask what makes C++ as powerful and flexible as it is, the answer would be its support for multiple types of programming, such as functional, OOP, procedural, and so on. So, today we will tell you everything you need to know about the fundamentals of C++, including its most essential features like Sets, Constructors, Polymorphism in C++, etc.

Datatypes

There are two types of data types in C++ – primitive (pre-defined) and non-primitive datatypes. Non-primitive ones are further divided into two categories: derived datatypes and user-defined datatypes.

Primitive data types are int, char, string, boolean, float, double, byte, short, and long.

Derived data types are: functions, arrays, pointers, and references

User-defined datatypes: structure, class, enum, union, typedef

Functions

A small piece of code for performing a task that can be used anywhere and any number of times in the program is known as a function. A function might or might not accept any data in the form of arguments or parameters.

Syntax for declaring a function –

return_type function_name (*list of arguments*);

Syntax for defining a function

return_type function_name (*list of arguments*) {      //body of the function definition }

A function can be defined anywhere in a C++ program, provided the function declaration is present before the function call.

Loops in C++

There are three types of loops that can be used in C++: for loop, while loop, and do-while loop. Among these three, ‘for’ and ‘while’ loops allow the control to enter the loop only if the test condition is satisfied. On the other hand, the do-while loop executes the following block statements and tests the condition. Hence, a do-while loop always executes at least once.

. for loop Syntax:

for ( start variable initialisation; test condition; upgradation) {   // Statements to be executed }

while loop Syntax:

while (test condition) {  // Statements to be executed // Updation statements are written inside the loop if any }

. do-while loop Syntax:

do {   // Statements to be executed } while (test condition)

Sets

The Standard Template Library (STL) of C++ consists of various containers such as arrays, sets, deques, list, map, and so on. Sets are an associative type of data container that stores the elements in a sorted manner, and the complexity related to the implementation of its data structure is 0(log n). They are one of the most useful components of C++ STL when implementing algorithms, as they only store unique elements in a certain order.

Each element in a set identifies itself, i.e., the values are keys to themselves. Hence, sets do not support indexing. Its elements are immutable. In other words, we can either insert an element into a set or delete an element from the set but cannot modify the elements. A specific strict weak order criterion is used to sort the set elements internally, using an internal object of Comparison type.

Following are the basic functions used in any set implementation:

begin() – A method returning an iterator to the first set element.

end() – A method used for returning an iterator to the next position of the last element of the set.

*it – It gives the value present at the position this iterator points to.

insert(n) – This method takes the value to be inserted into the set as its parameter and adds the value to the set

erase() – A method used for removing the elements from the set. It can take the value itself to be deleted or the iterator to the value as its argument.

size() – We can use the size() method with C++ std::set to determine the size of a set.

find(n) – This predefined method is used for searching for an element in a set. It takes the element to be searched for, ‘n’ in its argument, and returns an iterator pointing to that element.

OOP in C++

The four pillars of Object-Oriented Programming (OOP) are data abstraction, data encapsulation, polymorphism, and inheritance. Data Abstraction is the process of hiding unessential data and showing only the relevant data to the users and other entities. Wrapping up data content in a single unit called class is known as data encapsulation.Polymorphism is the feature that triggers different actions to be performed by a function when called, depending on the type of object it is invoked by. The feature of inheriting one class’s members by another is known as inheritance. Now, all these features are applied to the building blocks of OOP, i.e., class and objects.

The real-world entities are represented in the form of class and objects. A class is a user-defined data type consisting of certain attributes and methods. These attributes are known as data members, and the methods are called member functions. An instance of a class is known as its object. Every object belongs to a class. Memory is allocated to a class at the time of its instantiation.

Example: A class named Bike can have model, mileage, etc., as the data members, accelerate, apply_brakes, etc., as member functions. Its object can be a Royal_Enfield and its respective properties(attributes) and behaviors(methods).

Constructors

So, when we talk about class in C++, we are bound to talk about constructors too. Constructors are simply the member function of a class responsible for initializing the data members of the class. Having the same name as that of the class name identifies a constructor in a class. A constructor is called automatically by the compiler at the time of an instance creation for a class. Since constructors do not return any value, they are not required to have a return type.

Like any other member function of a class, constructors also have a prototype and definition. The syntax for the declaration and definition of a constructor is as follows:

//Prototype Constructor_name (datatype1 arg1, datatype2 arg2,…); //Here,  Constructor_name is same as the class_name
//Definition Constructor_name (arg1, arg2,…) {    //Required initialisations for the data members of the class   }

Go through the following example to get a better understanding of constructors in C++

#include <iostream> using namespace std;   class Book{     string title;     string author;     float price;       public:     Book(){                        // Constructor without parameters         title = “Wuthering Heights”;         author = “Emily Bronte”;         price = 109;     }     void show(){         cout << “Title: ” << title << endl;         cout << “Author: ” << author << endl;         cout << “Price: ” << price << endl;     } };   int main() {         Book object;    // Constructor is invoked     object.show();     return 0; }

Output:

The constructor can be defined outside the class as well, but it must be declared within the class always. The following syntax is followed in this case:

class class_name {      //private members public:       class_name (datatype1 arg1, dattatype2 ag2, …);                     // Constructor declaration        //Other public data members and member functions };   class_name::class_name (datatype1 arg1, dattatype2 ag2,… )    // Out of the class constructor definition {    //constructor definition consisting of    //essential initialisations }

A class can have more than one constructor when any of the following three conditions satisfy-

  • The constructors have different number of arguments
  • The constructors have different types of arguments
  • The constructors have different sequences of arguments

This scenario of a C++ class in Object Oriented Programming is termed as Constructor Overloading. It indicates the polymorphism feature of OOP.

Polymorphism

Polymorphism is one of the fundamental characteristics of OOP that usually occurs when a hierarchy of classes are related to each other via inheritance. When a call to member function triggers different types of actions based on the objects that call the function, it is known as Polymorphism.

Polymorphism in C++ is usually represented by function overloading, constructor overloading, and operator overloading.

Let’s take an example of constructor and function function overloading to understand about polymorphism clearly.

#include <iostream> using namespace std;   class Book{     string title;     string author;     float price;       public: // Constructor Overloading     Book(){                                                                           //Constructor1         title = “Wuthering Heights”;         author = “Emily Bronte”;         price = 109;     }     Book(string name, string writer){                           //Constructor2         title = name;         author = writer;     }   // Function Overloading     void show(){                                                              //show()-1         cout << “Title: ” << title << endl;         cout << “Author: ” << author << endl;         cout << “Price: ” << price << endl << endl;     }     void show(int n){                                                   //show()-2         cout << “Title: ” << title << endl;         cout << “Author: ” << author << endl;         cout << “Price: ” << n << endl;     } };   int main() {        Book object1;                                                                 //Constructor1 is invoked     Book object2(“Dark Matter”, “Blake Crouch”);      //Constructor2 is invoked     object1.show();                                                           //show()-1 is called     object2.show(250);                                                   //show()-2 is called     return 0; }

Output:

The Constructor1 initialises the three members with fixed values, whereas Constructor2 initialises two of the data members with the values passed as the arguments. Similarly, there are two show() functions – show() function displays all the pre-set three values whereas show(n) takes an integer value and displays it as the cost of the book along with the pre-set values of the other 2 data members.

Operator Overloading is slightly different from constructor and function overloading. C++ allows redefining the way an operator operates on user-defined data types such as objects and structures. For instance, we can change the way an addition operator ‘+’ works for two strings and use it to for their concatenation. 

So far, you must have developed a solid base on C++ and realised the significance of this versatile language in developing. If like C++, you want to more trending languages, we recommend you to start with Java Programming. Start learning with a variety of learning-filled free courses today!

About author

Carl Herman is an editor at DataFileHost enjoys writing about the latest Tech trends around the globe.