Friday, October 13, 2017

Lecture Notes 05

Object Oriented Programming: Lecture Notes 05

Author: A. El-Gadi/Faculty of Computer Engineering/Tripoli University

If not overridden, the default constructor would simply allocate memory when the class is instantiated i.e. an object is created. A class can have multiple constructors. To understand, how is this possible we need to understand the idea of function overloading.

 

Function overloading:


Function overloading is the ability to have more than one version of the function that differ only in their passing parameters, but have identical names and return types. Take the following example:

void func1(int x){cout<<"This is the INT version";}
void func1(double x){cout<<"This is DOUBLE double version";}

int main(){int y1; double y2;

func1(y1);//Output: This is the INT version
func1(y2);//Output: This is the DOUBLE version
return 0;
}


In the code above the appropriate function is called based on the passing parameter's type. The compiler will choose the version that matches or closely matches the type of the passing parameter. Therefore, if we pass a float in the code above, the function that takes double as passing parameter will be called.

void func1(int x){cout<<"This is the INT version";}
void func1(double x){cout<<"This is DOUBLE double version";}

int main(){float y;

func1(y);//Output: This is the DOUBLE version
return 0;
}


It is also possible to have overloaded functions for types of the same 'family' such as floats and doubles. However, this is not advisable because it does not meet the expectations of the programming community, which normally expects types of the same family to be cast to one another, rather than being treated differently. Therefore, the example below compiles and runs but is ill-designed:

void func1(float x){cout<<"This is the FLOAT version";}
void func1(double x){cout<<"This is DOUBLE version";}

int main(){float y1; double y2;

func1(y1);//Output: This is the FLOAT version
func1(y2);//Output: This is the DOUBLE version
return 0;
}


Class member functions can also be overloaded. Take the following TimePeriod class. Assume that minutes are as accurate a time as we desire to have. We also want to have a function to add minutes and a function to display the period of time.

class TimePeriod{private:
        int minutes;
        public:
        TimePeriod(){minutes=0;}
        void display(){int h,m; h=minutes/60; m=minutes-h*60;
                cout<<h<<':'<<m;}
        void addMinutes(int m){minutes+=m;}
        int get(){return minutes;}
        };



But it is also natural to add time in hours as well. We can include another member function to add time in hours, and our class would end up looking like this:

class TimePeriod{private:
        int minutes;
        public:
        TimePeriod(){minutes=0;}
        void display(){int h,m; h=minutes/60; m=minutes-h*60;
                cout<<h<<':'<<m;}
        void addMinutes(int m){minutes+=m;}
        void addHours(int h){minutes+=h;}
        int get(){return minutes;}
        };


However, a better approach that keeps the user of our class from deciding which function to choose when adding time is to overload functions to do the different tasks addMinutes and addHours do. This requires that we have minutes and hours as differentiated types.

class Minutes{public: int min;};
class Hours{public: int hours;};

class TimePeriod{private:
        int minutes;
        public:
        TimePeriod(){minutes=0;}
        void display(){int h,m; h=minutes/60; m=minutes-h*60;
                cout<<h<<':'<<m;}

        void addTime(Minutes m){minutes=minutes+m.min;}
        void addTime(Hours h){minutes=minutes+h.hours*60;}
        int get(){return minutes;}
        };

int main(){Minutes m1; Hours h1; TimePeriod tp1;
        m1.min=30; h1.hours=3;
        tp1.addTime(m1);//This will call the first overloaded addTime
        tp1.addTime(h1);//This will call the second overloaded addTime
        tp1.display();//Output: 3:30
        return 0;
        }

   

We can even include a function that accepts both hours and minutes and another one that accepts another period of time.

class Minutes{public: int min;};
class Hours{public: int hours;};

class TimePeriod{private:
        int minutes;
        public:
        TimePeriod(){minutes=0;}
        void display(){int h,m; h=minutes/60; m=minutes-h*60;
                cout<<h<<':'<<m;}

        void addTime(Minutes m){minutes=minutes+m.min;}
        void addTime(Hours h){minutes=minutes+h.hours*60;}
        void addTime(Hours h, Minutes m){addTime(h); addTime(m);}
        void addTime(TimePeriod tp){minutes=minutes+tp.get();}
        int get(){return minutes;}
        };

int main(){Minutes m1; Hours h1; TimePeriod tp1, tp2;
        m1.min=30; h1.hours=3;
        tp1.addTime(m1);//This will call the first overloaded addTime
        tp1.addTime(h1);//This will call the second overloaded addTime
        tp1.display();//Output: 3:30
       
        tp2.addTime(m1);//Adds 30 minutes
        tp2.addTime(tp1);//Adds 210 minutes
        tp2.addTime(h1,m1);//Adds 210 minutes
        cout<<'\n';
        tp2.display();//Output: 7:30

        return 0;
        }

 

Constructor overloading:


To return to our initial concern -that of having multiple constructors- we will add that constructors too can be overloaded. This allows users of the class to initialize objects with the desired values. A constructor that takes parameters is called parametric constructor as opposed to the default constructor that takes no parameters. The following is the class TimePeriod after adding some parametric constructors. In the function main you can find the syntax for the usage of parametric constructors.


class Minutes{public: int min;};
class Hours{public: int hours;};

class TimePeriod{private:
        int minutes;
        public:
        TimePeriod(){minutes=0;}
        TimePeriod(Minutes m){minutes=m.min;}
        TimePeriod(Hours h){minutes=h.hours*60;}
        TimePeriod(Hours h, Minutes m){minutes=h.hours*60+m.min;}
       
        void display(){int h,m; h=minutes/60; m=minutes-h*60;
                cout<<h<<':'<<m;}

        void addTime(Minutes m){minutes=minutes+m.min;}
        void addTime(Hours h){minutes=minutes+h.hours*60;}
        void addTime(Hours h, Minutes m){addTime(h); addTime(m);}
        void addTime(TimePeriod tp){minutes=minutes+tp.get();}
        int get(){return minutes;}
        };

int main(){Minutes m1; Hours h1;
       m1.min=40; h1.hours=2;

       TimePeriod tp1(m1);//Initialize with Minutes object
       TimePeriod tp2(h1);//Initialize with Hours object
       TimePeriod tp3(h1,m1);//Initialize with Hours and Minutes

       tp1.display();//Output: 0:40
       tp2.display();//Output: 2:0
       tp3.display();//Output: 2:40
       return 0;
    }

   





Monday, October 9, 2017

Lecture Notes 04

Object Oriented Programming: Lecture Notes 04

Author: A. El-Gadi/Faculty of Computer Engineering/Tripoli University

Objects of the following triangle class can easily be assigned inconsistent values. The triangle inequality rule, for example, is not guaranteed to hold; because side1, side2 and side3 are public (see the code below).

class Triangle{public:
        double side1;
        double side2;
        double side3;
        double perimeter(){return side1+side2+side3;}
        };


int main(){Triangle t1;
    t1.side1=10; t1.side1=7; t1.side1=1.5;/*triangle inequality rule violated*/
    return 0;
    }



In what follows, we will advance slowly towards a correct design solution to this problem by exploring intermediate steps and finding out how object oriented principles can solve the emerging issues.

One way to solve this problem is to inform our class users to adhere to the rules that govern a triangle when assigning values to its sides of a triangle through the use of comments. Our class would look like the following:


class Triangle{public:
        /*When assigning values to side1, side2, and side3, make sure not to violate the triangle inequality; that is, never let any side be greater than the sum of the two other sides*/   
        double side1;
        double side2;
        double side3;
        double perimeter(){return side1+side2+side3;}
        };



This is of course is a very small improvement because it relies solely on how disciplined the user of the class is. The correct approach, which employs the principles of object oriented programming, is to disallow any direct assignment of the sides of the triangle by hiding them i.e. by making them private, as shown in the code below:


class Triangle{private:
        double side1;
        double side2;
        double side3;
        public:       
        double perimeter(){return side1+side2+side3;}
        };


The class above is, of course, useless; as there is no way to access its member variables outside the scope of the class. Therefore, we need to supply public member functions to access our private members setter/getter pairs. It should also be obvious that, setter member functions -aka mutator methods- are the appropriate place to validate data before assigning it to the class members. Accordingly, our class should end up looking like the following:

class Triangle{private:
        double side1;
        double side2;
        double side3;

        public:   
        void setSide1(double x){
            if(
side2+side3>x&&side2+x>side3&&side3+x>side2){side1=x;}
            }

        double getSide1(){return side1;}

        void setSide2(double x){
            if(
side1+side3>x&&side1+x>side3&&side3+x>side1){side2=x;}
            }

        double getSide2(){return side2;}

        void setSide3(double x){
            if(
side2+side1>x&&side2+x>side1&&side1+x>side2){side3=x;}
            }

        double getSide3(){return side3;}

        double perimeter(){return side1+side2+side3;}
        };


The class above checks if the triangle inequality is met before setting the value of a supplied side length. The class is still useless, nonetheless, because when a triangle object is created, the initial values of side1, side2,and side3 will hold whatever value there is in the memory allocated for the object. It is not guaranteed that those values would not, by coincidence, be in disagreement with the conditions: side2+side3>x; side1+side3>x; side2+side1>x above. Let us assume, for example, that side1, side2,and side3 hold the values 98765445.322222, 734853.987, 9383929.33002 at the moment of the object's creation. If we wish to set the sides to the values 10.5 7.3 and 14.11 our attempt would fail for every side. To solve this problem, it seems reasonable to find a way to perform validation only when the other two sides have been set. This means that we should keep track of which sides have been set and which ones have not been set. The obvious programming technique to employ in such a situation is include a flag corresponding to each side. The flag value is set to true when the corresponding side is set. The initial value of each flag should be false, but for the time being we will have to defer the treatment of this issue to the next step. Our flags belong naturally to the private part of the class for three reasons: 1) They should be safeguarded from any tampering. 2) They are not an intrinsic part of the concept of a triangle. Their reason of being in the class is that of practicality. 3) They constitute an added complexity that is best kept hidden from the user.

class Triangle{private:
        double side1;
        bool flag1;
        double side2;
        bool flag2;
        double side3;
        bool flag3;

        public:   
void setSide1(double x){
            if(!(flag2&&flag3)){side1=x; flag1=true;}
            else{
            if(side2+side3>x&&side2+x>side3&&side3+x>side2){side1=x; flag1=true;}}
            }

        double getSide1(){return side1;}

        void setSide2(double x){
            if(!(flag1&&flag3)){side2=x; flag2=true;}
            else{
            if(side1+side3>x&&side1+x>side3&&side3+x>side1){side2=x; flag2=true;}}
            }

        double getSide2(){return side2;}

        void setSide3(double x){
            if(!(flag2&&flag1)){side3=x; flag3=true;}
            else{
            if(side2+side1>x&&side2+x>side1&&side1+x>side2){side3=x; flag3=true;}}
            }

        double getSide3(){return side3;}

        double perimeter(){return side1+side2+side3;}
        };



This class should work fine, if only we had a way to initialize the flags to false. Fortunately, OOP allows programmers to control the creation of an object through constructors. Constructors can be thought of as member functions that are executed at the moment of an object's instantiation. They are distinguished by having a name identical to the class' name and no return values. Here is our Triangle class after adding a constructor that initializes all flags to false.

class Triangle{private:
        double side1;
        bool flag1;
        double side2;
        bool flag2;
        double side3;
        bool flag3;

        public:   
        void setSide1(double x){
            if(!(flag2&&flag3)){side1=x; flag1=true;}
            else{
            if(side2+side3>x){side1=x; flag1=true;}}
            }

        double getSide1(){return side1;}

        void setSide2(double x){
            if(!(flag1&&flag3)){side2=x; flag2=true;}
            else{
            if(side1+side3>x){side2=x; flag2=true;}}
            }

        double getSide2(){return side2;}

        void setSide3(double x){
            if(!(flag2&&flag1)){side3=x; flag3=true;}
            else{
            if(side2+side1>x){side3=x; flag3=true;}}
            }


        double getSide3(){return side3;}

        double perimeter(){return side1+side2+side3;}

        Triangle(){flag1=false; flag2=false; flag3=false;}
        };

int main(){Triangle t; /*Triangle() is executed and thus all flags are set to false*/
       t.setSide1(10); t.setSide2(20); t.setSide3(150);
       cout<<t.getSide1()<<' '<<t.getSide2()<<' '<<t.getSide3()<<endl;
       return 0;
      }


We will have more to say about constructors later.

Friday, October 6, 2017

Lecture Notes 03

Object Oriented Programming: Lecture Notes 03
Author: A. El-Gadi/Faculty of Computer Engineering/Tripoli University


Member functions:


In addition to member variables, classes can have member functions; also known as methods. Member functions are chosen to be expressive of how a class behaves. They encapsulate the class behavior in the class in the same way member variables encapsulate class attributes. The following Rectangle class illustrates the use of member functions and their invocation.

class Rectangle{public:
        double width;
        double height;
        double area(){return width*height;}
        double perimeter(){return 2*(width+height);}
        };

int main{Rectangle r1,r2;
    r1.height=10; r1.width=30.5;
    r2.height=100; r2.width=70;

    double temp;
    temp=r1.area();
    temp=r2.perimeter();
    return 0;
    }



The member functions above can be rewritten outside the body of the class using the scope operator :: , whose function is to tell the compiler to which class a function belongs. Declarations inside the class body, however, must be supplied. The scope operator becomes even more important with large functions, whose implementation if included in the class body can render the class definition unreadable. The following example illustrates the use of scope operator with two classes that have functions with similar names.

class Rectangle{public:
        double width;
        double height;
        double area();
        double perimeter();
        };

double Rectangle::area(){return width*height;}
double Rectangle::perimeter(){return 2*(width+height);}

class Circle{public:
        double radius;
        double area();
        };


double Circle::area(){return 3.14159*radius*radius;}

int main{Rectangle r1; r1.height=10; r1.width=30.5;
    Circle c1; c1.radius=5;

    double temp;
    temp=r1.area();//Returns the value 10*30.5
    temp=c1.area();//Returns the value 3.14159*5*5
    return 0;
    }


Objects as member variables:

Member variables are not limited C++ basic types. User defined types can also be member variables. Suppose that we want to design a class for a rectangular door which has a height a width and thickness, and whose area and perimeter we will calculate using member functions. Our door class should look something like this:

class Door{public:
        double width;
        double height;
        double thickness;
        double area(){return width*height;}
        double perimeter(){return 2*(width+height);}
        };


You should be able to notice that Door has every attribute and member function that the class Rectangle has. This is a good situation to include Rectangle object as a member of Door and reuse the functionality of the class Rectangle. Our new class should look like the following. Notice how the height and width are accessed through the Rectangle object:


class BetterDoor{public:
        Rectangle r;
        double thickness;
        };

int main{BetterDoor bd1;
    bd1.r.width=100; bd1.r.height=200; bd1.thickness=5;
    return 0;
    }


Data and complexity hiding:

One of most important tenets of the object oriented philosophy is that of data hiding and complexity hiding. Data hiding is the principle that states that any data that the user of the class does not need to see and manipulate should be hidden from him/her. This serves two goals. First the hidden data becomes inaccessible and thus impossible to tamper with, and any data that strictly belongs to the inner workings of the class is hidden to facilitate an effortless understanding of the class.

In the class BetterDoor above, some complexity has arisen from the inclusion of a Rectangle object. Accessing width and height now has become less natural than before; because normally the height and width of a door are never thought of as the height and width of the rectangle the comprises the door. Nevertheless, when using the class BetterDoor we could only access those two dimensions in the mentioned unnatural way. To solve this problem, we can hide the Rectangle object using the private keyword. The private keyword makes what follows it accessible only to the member functions of the class, and any attempt to access them outside the class' scope would result in a compilation-time error. After making the rectangle object private we can add member functions to access it, and change it in the natural way we desire. The resultant redesign looks like this:

class EvenBetterDoor{public:
        Rectangle r;
        public:
        double thickness;
        void setH(double x){r.height=x;}
        double getH(){return r.height;}
        double setW(double x){r.width=x;}
        double getW(){return r.width;}
        };

int main{EvenBetterDoor bd1;
    bd1.setW(100); bd1.setH(200); bd1.thickness=5;
    temp=bd1.getW();
    temp=bd1.getH();
    return 0;
    }


Hiding data is also important when directly changing that it can result in a corrupted object. Take for example the case of a triangle class defined by the lengths of its three sides. It would seem straightforward that we can assign the lengths to the sides directly by allowing the sides of the triangle to be public as follows:

class Triangle{public:
        double side1;
        double side2;
        double side3;
        double perimeter(){return side1+side2+side3;}
        }


But once we realize that the lengths of the sides of the triangle are governed by the triangle inequality rule, which states that for any triangle the sum of two sides is greater than or equal to the remaining side. Therefore, a better design of a triangle class should take into account that this rule is never violated. The first step in ensuring such a behavior is to hide the sides of the triangle.

Monday, October 2, 2017

Lecture Notes 02

Object Oriented Programming: Lecture Notes 02
Author: A. El-Gadi/Faculty of Computer Engineering/Tripoli University

C-style structs come close to achieving one of the central pillars of object oriented programming called encapsulation. Encapsulation in its fullest sense is the principle of encapsulating all attributes and behavior of some type as an integral part of the type. To achieve encapsulation in the fullest sense of the term, we need more than C-style structs for reasons that will become clear later. In the terminology of OOP this concept is called class. Classes are used to define and describe kinds of things (tables, bottles, cars, human beings, mathematical equations, numbers and so on). Each class is a general statement about the kind it describes. In C++, the class syntax in its simplest can look like the following:

class Rectangle{public:
        double height;
        double width;
        };


The class above is a class that defines a rectangle. The keyword public is used to make the attributes or member variable that come after it visible to the outside. Its importance will become clear later in the course.

The following example illustrates how to use our simple class:

class Rectangle{public:
        double height;
        double width;
        };

#include<iostream>

int main(){Rectangle r1; double temp;
temp=r1.height+r1.width;
}


Notice how we could access the member variable of the class using the dot operator. The syntax, as you might have noticed, is akin to the struct syntax. Also note that the new type Rectangle is not preceded by the keyword class when defining objects of its type.

Saturday, September 30, 2017

Lecture Notes 01

Object Oriented Programming: Lecture notes 1

Author: A. El-Gadi/Tripoli University

1) The evolution of computer programming

The history of computer programming can be summarized as the quest to make programming computers more natural to human beings. In that sense, the story of the evolution of programming is the story making programming more compatible with the natural way people think about the world around them.
At the dawn of computing, we were content with being able to enter programs into computers in binary format. Where each machine instruction is represented by a unique binary code. Writing a program in machine code was indeed a tedious and error-prone task which constituted a barrier in the way of building larger and more complex program. Listing 1 shows an example of machine code in binary along with the corresponding assembly code and the c language code from which the machine code was produced.
The next step in the evolution of programming was the invention of assembly language, which is basically a set of mnemonics that correspond to machine instructions. Those mnemonics were chosen to be descriptive of what an instruction did. Simple as it is, the principle upon which assembly was based, greatly simplified the task of programmers making them more productive and more capable of tackling more complex tasks. However, assembly suffered from a serious shortcoming, namely that its syntax is an almost direct mapping of the machine architecture. This meant that programming in assembly involved following closely the way the machine operated; see listing 1 to appreciate what adding 4 numbers and storing them in a variable looks like. This also meant that assembly programmers had to think about the specifics of the machine they were programming in order to accomplish their tasks.
High level programming languages sought to overcome this limitation by separating the logic part from the machine part. This is called abstraction -i.e. Abstracting the language from the details of the machine. High level language design philosophy revolves around making the programmer thing about the problem at hand -its logical, relational, structural components- and forgetting about the hardware at hand. The details of converting (compilation) a high level code to the proper machine code is left to the compiler which ”knows” the architecture of the machine in which it is installed.

#include<stdio.h>
void main(){int h=15,i=31,j=63,k=127,m=255,n=511;
h=i+j+k+m;}

01) 1100 0111 0100 0101 1110 1000 0000 1111 0000 0000 0000 0000 0000 0000     mov    [bp-0x18],15
02) 1100 0111 0100 0101 1110 1100 0001 1111 0000 0000 0000 0000 0000 0000     mov    [bp-0x14],31
03) 1100 0111 0100 0101 1111 0000 0011 1111 0000 0000 0000 0000 0000 0000     mov    [bp-0x10],63
04) 1100 0111 0100 0101 1111 0100 0111 1111 0000 0000 0000 0000 0000 0000     mov    [bp-0xc],127
05) 1100 0111 0100 0101 1111 1000 1111 1111 0000 0000 0000 0000 0000 0000     mov    [bp-0x8],255
06) 1100 0111 0100 0101 1111 1100 1111 1111 0000 0001 0000 0000 0000 0000     mov    [bp-0x4],511
07) 1000 1011 0100 0101 1111 0000                                             mov    ax,[bp-0x10]
08) 1000 1011 0101 0101 1110 1100                                             mov    dx,[bp-0x14]
09) 0000 0001 1100 0010                                                       add    dx,ax
10) 1000 1011 0100 0101 1111 0100                                             mov    ax,[bp-0xc]
11) 0000 0001 1100 0010                                                       add    dx,ax
12) 1000 1011 0100 0101 1111 1000                                             mov    ax,[bp-0x8]
13) 0000 0001 1101 0000                                                       add    ax,dx
14) 1000 1001 0100 0101 1110 1000                                             mov    [bp-0x18],ax 

Listing 1: A C language code along with the corresponding machine and assembly code.
This big step is what enabled programmers to write statements like h=i+j+k+m without ever thinking of how this line is going to actually be executed in the machine.
Carrying on with motif of making programming languages even more natural, object oriented programming OOP exploited the fact that the most natural way a human being thinks about the world is thinking about it as being made up of objects with properties and behavior and the relations that govern how these objects interact. By enabling programmers to model the way of everyday thinking, the object oriented methodology avoids many of the problems inherent in purely procedural programming languages.

2) C struct’s as a stepping stone to OOP

In the world of C programming the closest one can get to object oriented programming is through using structs. Let us say that one wishes to write a program to compute the area of a rectangle. Let us compute the the area of three of them in our code. A purely procedural approach without using structs would look something like this: 
#include<stdio.h>

float area(float side1, float side2){return side1*side2;}

void main(){float r1s1=10,r1s2=20,r2s1=30,r2s2=100,r3s1=200,r3s2=300;
float temp;
temp=area(r1s1,r1s2);
temp=area(r2s1,r2s2);
temp=area(r3s1,r3s2);
} 

In the above code we have to take special care not to mix up subscripts and every time we invoke the area function we would have to pass the two sides as parameters.
The following example illustrates the problem even more clearly. Let us write a code to compute the circumference of a heptagon. 

#include<stdio.h>

float circumference(float side1, float side2, float side3, float side4, float side5, float side6, float side7){return side1+side2+side3+side4+side5+side6+side7;}

void main(){
float p1s1=10,p1s2=20,p1s3=30,p1s4=15,p1s5=25,p1s6=16,p1s7=13;
float p2s1=5,p2s2=3,p2s3=5,p2s4=6,p2s5=7,p2s6=2,p2s7=3;
float p3s1=100,p3s2=130,p3s3=140,p3s4=70,p3s5=80,p3s6=50,p3s7=50;

float temp;
temp=circumference(p1s1,p1s2,p1s3,p1s4,p1s5,p1s6,p1s7);
temp=circumference(p2s1,p2s2,p2s3,p2s4,p2s5,p2s6,p2s7);
temp=circumference(p2s1,p2s2,p2s3,p2s4,p2s5,p2s6,p2s7);
}
 

 
A solution that uses structs avoids the problem of having to pay special attention to each passing parameter encapsulating all the information about our object, the heptagon, in one struct.
#include<stdio.h>

struct Heptagon{float side1;float side2;float side3;float side4;float side5;float side6;float side7;};

float circumference(struct Heptagon p){return p.side1+p.side2+p.side3+p.side4+p.side5+p.side6+p.side7;}
/*struct here is passed by value to avoid introducing several new ideas in the same time*/

void main(){struct Heptagon p1,p2,p3;

p1.side1=10,p1.side2=20,p1.side3=30,p1.side4=15,p1.side5=25,p1.side6=16,p1.side7=13;
p2.side1=5,p2.side2=3,p2.side3=5,p2.side4=6,p2.side5=7,p2.side6=2,p2.side7=3;
p3.side1=100,p3.side2=130,p3.side3=140,p3.side4=70,p3.side5=80,p3.side6=50,p3.side7=50;

float temp;
temp=circumference(p1);
temp=circumference(p2);
temp=circumference(p3);
} 

Another advantage of struct’s is that of abstracting from the details of that which it encapsulates. What this means is that after preparing the object we can forget about its details. Let’s say we have a pyramid with rectangular base. We want write a code to compute its volume as well as the area of its base. We will first implement a solution without structs. A pyramid of a rectangular base can be determined by the side lengths of the base rectangle and its height from the base. Let us assume that we want to be able to calculate both its volume and the base area. A solution that does not employ structs looks like this:
#include<stdio.h>

float volume(float height, float baseside1, float baseside2){return height*baseside1*baseside2/3;}
float basearea(float baseside1, float baseside2){return baseside1*baseside2;}

void main(){float h=7,bs1=4,bs2=5;
float temp;
temp=volume(h,bs1,bs2);
temp=basearea(bs1,bs2);
} 

The shortcoming of this approach is that there is no check on whether the parameters passed really represent the correct entities. For example, basearea can be mistakenly called like this basearea(bs1,h) leading to disastrous consequences and a debug nightmare.
A better approach is to employ structs let each function pick out the right set of struct variables from the struct. This way, we are protected from mistakes of the kind mentioned above. 

#include<stdio.h>

struct Rectpyramid{float height; float baseside1; float baseside2;};

float volume(struct Rectpyramid pyr){return pyr.hight*pyr.baseside1*pyr.baseside2/3;}
float basearea(struct Rectpyramid pyr){return pyr.baseside1*pyr.baseside2;}

void main(){struct Rectpyramid pyr1;
pyr1.height=7; pyr1.baseside1=4; pyr1.baseside2=5;
float temp;
temp=volume(pyr1);
temp=basearea(pyr1);
}

Thursday, June 29, 2017

Simple Array Class Template

/*This code was written by A. El-Gadi of Tripoli University for educational purposes. It is an implementation of a simple array class template.  For any questions  and discussion use the comment section below.*/

#include <iostream>

using namespace std;

template<typename T>
class Array{private:
        T* parray;
        int size;

        public:
        Array():parray(NULL),size(0){};
        Array(int sz):parray(new T[sz]),size(sz){};
        Array(T* parr,int sz):parray(new T[sz]),size(sz){for(int i=0;i<size;i++){parray[i]=parr[i];}}
        void printarray(){cout<<"[ "; for(int i=0;i<size;i++){cout<<parray[i]<<' ';} cout<<']'<<endl;}
        T getelement(int i){return parray[i];}
        void setelement(int i,T telem){parray[i]=telem;}
        void copyarray(Array<T> art){delete []parray; parray=new T[art.size]; size=art.size; for(int i=0;i<size;i++){parray[i]=art.getelement(i);}}
        ~Array(){delete []parray;}
};

int main(){

Array<int> ia(10);
ia.printarray();

float finita[5]={1,2,3,4,5};

Array<float> fa1(finita,5);

fa1.printarray();

Array<float> fa2;
fa2.copyarray(fa1);
fa2.printarray();
}

Wednesday, June 21, 2017

Variations on Templates

/*This code was written by A. El-Gadi of Tripoli University for educational purposes. It offers variations on the template theme and their implications. The classes used here are not necessarily useful, as they were designed for the sole purpose of offering a synoptic peek at the template syntax.  For any questions  and discussion use the comment section below.*/

#include <iostream>

using namespace std;

class AA{public: int data1; double data2;};
class BB{public: int data1; double data2;};

template<typename T1,typename T2>
class BoxOf2{private:
        T1 var1;
        T2 var2;
         public:
            double sum1(){return var1+var2.data1;}//The presence of this function dectates that T2 must have a public member variable called data1
        double sum2(){return var1+var2.data2;}//The presence of this function dectates that T2 must have a public member variable called data1
        T1 &getvar1(){return var1;}//We let get return a reference here to allow for left-hand-side assignment. See below. This consideration is not related to templates per se.
        T2 &getvar2(){return var2;}//We let get return a reference here to allow for left-hand-side assignment. See below. This consideration is not related to templates per se.
        void setvar1(T1 v1){var1=v1;}
        void setvar2(T2 v2){var2=v2;}                   
        };

int main(){

BoxOf2<int,AA> bia1; BoxOf2<int,AA> bia2; BoxOf2<float,AA> bfa; BoxOf2<int,BB> bib1; BoxOf2<int,BB> *pbib;//Box<int,AA> Box<float,AA>  Box<int,BB> are strictly different types. As such, they cannot be assign to each other nor cast to each other.

bia1.setvar1(10);
bia1.setvar2(AA());//Set var2 with an object of type AA. If they exist, parametrized constructors can be used here.
bia1.getvar2().data1=100;//This is possible because getvar2 returns a reference.
bia1.getvar2().data2=1000;//This is possible because getvar2 returns a reference.
cout<<bia1.getvar1()<<endl;
cout<<bia1.getvar2().data1<<endl;
cout<<bia1.getvar2().data2<<endl;

bia2=bia1;//bia1 and bia2 are of the same type this why they can be assigned to each other. They are both of type BoxOf2<int,AA>


pbib = new BoxOf2<int,BB>();//Example of using the new operator to create and object in the runtime.

bib1.setvar1(11);
bib1.setvar2(BB());//Set var2 with an object of type AA. If they exist, parametrized constructors can be used here.
bib1.getvar2().data1=111;
bib1.getvar2().data2=1111;
BoxOf2<int,BB> bib2(bib1);//Copy constructor.
*pbib=bib2;
cout<<pbib->getvar1()<<endl;
cout<<pbib->getvar2().data1<<endl;
cout<<pbib->getvar2().data2<<endl;

delete pbib; //delete as usual.

return 0;
}