Classes, Inheritance, and Virtual Methods

Atharva Dubey
2 min readMay 25, 2021

The previous post talked about how I will be accelerating various machine learning algorithms for various platforms, but first, I would first go through some rudimentary C++ features that would be required. This post would contain details about classes in C++ and what all can be done with them, mainly inheritance. Taking inspiration from PyTorch, all the classes that would be written would inherit an abstract class. The intuition behind doing so is as follows — One, that all classes to be written would definitely have the basic functions required, and second, since most of the classes would have a forward and a backward method (again, PyTorch inspired, these are the basic methods being talked about), this can help us create a branch table for the kernel dispatcher, as pointers of a virtual class are allowed. One can always create a pointer to the class method and create something similar to an unordered map using a key and the function pointer to call the required kernel. The final version of the kernel dispatcher would look something similar.

Establishing the need for inheriting classes, let’s come to the issue at hand, classes in C++, and how to inherit them. Object-oriented programming in C++ is quite simple, and a class can be created as follows —

Inheritance in C++ is more or less similar to python. In python where one specifies the parent class in parenthesis, in C++ one writes the parent class in front of the class declaration separated by a :and the visibility specifier. Note that the pointer which is of the type parent class can always point to a class that is inherited from the parent class. The following code block demonstrates this —

We wouldn't be doing the C Language much justice if we completely discard it for the lack of keyword class. One can always emulate classes, objects, and for that matter, object-oriented programming in its entirety using structs. Consider the following piece of code —

Thus it can be seen that even in pure C, one can get the functionalities of object-oriented programming if it is ever required.

In C++, a class that has at least one virtual method present in it is called an abstract class. All the classes which inherit such a class must override all the virtual methods otherwise they too become an abstract class. To make a method virtual, add the virtualkeyword in front of it, for example — virtual void print() = 0;.

So this was all about classes and inheritance in C, C++ and how to create a base class. The next post would talk about lambda functions, function pointers, templates, functors, which would be widely used in writing SYCL kernels.

Next in series — https://atharvadubey26.medium.com/functors-lambdas-and-function-pointers-a3dad53fc91d

--

--

Atharva Dubey
0 Followers

A recent BITS Pilani graduate. Passionate about the field of Deep Learning and High performance Computing