Posted in C++, GSoC, Python

Diamond inheritance: Python and C++ perspective

This post is a follow up from . I’ll expand on the other common and deadly inheritance issue, i.e the diamond inheritance problem. This problem is often not seen in small programs, but is easily encountered when working in an OOP environment, and also is not very easily detected. If you’re seeing weird / unexpected results in an OOP program, this should be one of the highest priority check on your checklist !

Alright, so before explaining what diamond inheritance is, I would like to explain what is multiple inheritance. No multiple inheritance == No diamond inheritance issues ever encountered !

Multiple inheritance is when say you have one class (say child), which is inheriting from two parent classes (say mother and father).

Now to put the issue into perspective, let’s additionally say that both mother and father class are inheriting from a class human. Thus both mother and father will derive some common methods from the human class. Let’s say it’s the eye_colour() (and only eye_colour() for simplicity).

What about the child class then ?
What should be the value of eye_colour() for child class ? Should it be taken from mother class or should it be taken from father class ?

The answer is – It’s language and implementation dependent.
For c++, this kind of a code will not even compile, and will force you to use some form of virtual keyword in order to resolve your problem.

For Python, different versions have different Method Resolution Orders defined (MROs). In short it is a depth first search, so suppose if we use multiple inheritance in Python using:

class Child (Mother, Father):
    pass

Then the Child class will get Mother class’s function eye_colour, since Mother was inherited first and then Father was inherited.
Similarly if we have declared Child class as:

class Child (Father, Mother):
    pass

Then the Child class will get Father class’s function eye_colour since Father was inherited first.

Kindly note that Python had several different algorithms for deciding the Method resolution in the past, so if you try it on older python versions, be sure to check what method resolution order did they use !
The above explanation for resolution is with reference to the MRO used with Python 3.

Note that Java doesn’t support multiple inheritance, and so this will never arise as an issue for the Java programmers 😉 .

Complete code for testing the Python’s method resolution order:

class Human(object):
    def eye_colour(self):
        print('Human eye')

class Mother(Human):
    def eye_colour(self):
        print('Mother eye')

class Father(Human):
    def eye_colour(self):
        print('Father eye')

class Child(Mother, Father):
    pass

newborn = Child()
newborn.eye_colour()

Try changing the order of Mother and Father while inheriting and see the difference in output !

PS: If it isn’t evident from the name, the problem is called diamond problem simply because the shape that’s formed when you draw the inheritance tree on paper.

     Human
    /      \
Mother    Father
    \      /
    Children

Similar to a diamond (if you’ve ever seen a diamond suite in a deck of cards :p ).

Thanks for reading !

Advertisements
Posted in C++

Word List – IARCS Problem Archive

Problem Link.

This is a nice excercise on the C++ STL Library. For those who aren’t familiar with it (for otherwise you wouldn’t be reading this article) , the best data structure for this will be the set. Continue reading “Word List – IARCS Problem Archive”

Posted in C++

ZCO 2013 – Solution : Tournament

The problem statement is described here.

The first impulse would be to calculate all the match revenues and then sum up… but it would be O(n^2) which isn’t good enough for the second subtask.

The key to the problem lies in an observation. Let’s consider an examples and then generalise it.

Let us take a different example than the given sample case.

4

3 10 7 5

Now the revenues for each match are :

10-5 +10-7 + 10-3 + 7-5 + 7-3 + 5-3 = 23

but wait that’s not what we will do… Look at it in the following manner :

Continue reading “ZCO 2013 – Solution : Tournament”

Posted in C++

Making a User friendly menu in old compilers for c++

This post is specially for those poor students who still have to use older compilers (Like Turbo C++). What I really mean by saying old is that a compiler supporting <CONIO.H > . This is no standard header file (and there is a specific reason to it too) but helps in creating Better interface for the USER.

What do we actually do to create a graphical interface ? We create colored illusions which make it seem that the interface is interactive. The top commands for this work are :

void textbackground(int );

void textcolor(int);

void gotoxy(int,int);

void clrscr(void);

char& getch(void);

Now to the working :

What happens when we have a menu and we want the current item to look like it’s selected, the special emphasis is brought about by a different color. Same thing we will also do here. Now a bit of coding manipulations :

Code for making a menu (without graphic interface) :

char* menu_items[] = {"Item 1","Item 2","Item 3"};   //Change these as per requirement
int n=3; // This variable stores the number of menu items we have
for(int i=0;i<n;i++)

{
     cout  <<   i+1   <<  " "  ;
     puts(menu_items[i]);
}                //Insert some command for pausing if required

This loop will display all our menu items along with their serial number.
Now a simple example on using the coloring commands
The output is like this :-

Plain menu
Plain menu without any graphical interface

Now the basic trick is to detect what button the user has pressed. To do this we will use the getch() command. {Note that getch() can appear on the right side of an expression and also as a normal function call}. The getch() command returns us the ascii value of the key we have hit. The tricky part here is that when the user presses an arrow key, the ascii value returned is not just one but two, So we need not only one getch() but two of them.

Continue reading “Making a User friendly menu in old compilers for c++”

Posted in C++

Overloading operator’s (in C++)

Here I will talk about overloading. Let’s start by formally defining what overloading is :

Specifying more than one definition’s for a function is called overloading.

Why do we need it ?

Now let’s say I have made a sort function. This function is sufficient for sorting an integer array, but what about an array with decimal number’s or a string. Again for sorting these data types we need more functions consisting of the same algorithm. Suppose we wanted to sort 4 different types of data types, we will have to make four different functions, and every-time I call the function I will need to decide what function to call. Wouldn’t it be nice if the compiler itself decided which function to call or if there were a self adjusting mechanism within the function to adjust according to input. This is why we need overloading. There is another mechanism to achieve the same and that is called a template, but overloading makes it easier to read the code at many occasions.

How it works ?

If you’ve been using standard c++ input methods then the familiar command cin and cout use operator >> and << respectively for functioning. Now these operators are actually overloaded. << and >> are the right shift and left shift operator’s originally, but the iostream file that we include in our programs has overloaded these operators to the extraction and insertion operators and thus now they function like that when used with cin and cout. These operators function as normal when not used with cin and cout.

This is how overloading works. Now to get to the implementation part, we will take up an example to get this better.

Let us make our own class for representing a fraction. A fraction has two parts, a numerator and a denominator, so our class will also have these two information. Here is the class prototypes :
Continue reading “Overloading operator’s (in C++)”

Posted in C++

Prime numbers

Prime numbers (Definition) :-

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Now the numbers which are prime follow the above condition. If we ask to write a program which identifies a prime number, the first approach would be by brute force, i.e to check for every number between 2 and the number itself and then use a flag to indicate whether a our program found a divisor or not. Then on the basis of the value of the flag we can say if it is a prime number or not. Continue reading “Prime numbers”