Set - 3

Question 1 :

Explain term POLIMORPHISM and give an example using eg. SHAPE object: If I have a base class SHAPE, how would I define DRAW methods for two objects CIRCLE and SQUARE ?

POLYMORPHISM : A phenomenon which enables an object to react differently to the same function call.
in C++ it is attained by using a keyword virtual

Example

``````public class SHAPE{
public virtual void SHAPE::DRAW()=0;
}``````

Note here the function DRAW() is pure virtual which means the sub classes must implement the DRAW() method and SHAPE cannot be instatiated

``````public class CIRCLE::public SHAPE{
public void CIRCLE::DRAW()
{
// TODO drawing circle
}
}

public class SQUARE::public SHAPE{
public void SQUARE::DRAW(){
// TODO drawing square
}
}``````

now from the user class the calls would be like
globally
SHAPE *newShape;

When user action is to draw

``````public void MENU::OnClickDrawCircle(){
newShape = new CIRCLE();
}

newShape = new SQUARE();
}

the when user actually draws

public void CANVAS::OnMouseOperations(){
newShape->DRAW();
}``````

``````class SHAPE{
public virtual Draw() = 0; //abstract class with a pure virtual method
};

class CIRCLE{
public int r;
public virtual Draw() { this->drawCircle(0,0,r); }
};

class SQURE
public int a;
public virtual Draw() { this->drawRectangular(0,0,a,a); }
};``````

Each object is driven down from SHAPE implementing Draw() function in its own way.

Question 2 :

Describe PRIVATE, PROTECTED and PUBLIC – the differences and give examples?

``````class Point2D{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
};

Point2D MyPoint;``````

You cannot directly access private data members when they are declared (implicitly) private:

``````MyPoint.x = 5; // Compiler will issue a compile ERROR
//Nor yoy can see them:
int x_dim = MyPoint.x; // Compiler will issue a compile ERROR``````

On the other hand, you can assign and read the public data members:

``````MyPoint.color = 255; // no problem
int col = MyPoint.color; // no problem``````

With protected data members you can read them but not write them:

``````MyPoint.pinned = true; // Compiler will issue a compile ERROR

bool isPinned = MyPoint.pinned; // no problem``````

Question 3 :

What is a COPY CONSTRUCTOR and when is it called?

A copy constructor is a method that accepts an object of the same class and copies it's data members to the object on the left part of assignement:

``````class Point2D{
int x; int y;

public int color;
protected bool pinned;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
public Point2D( const Point2D & ) ;
};

Point2D::Point2D( const Point2D & p ){
this->x = p.x;
this->y = p.y;
this->color = p.color;
this->pinned = p.pinned;
}

main(){
Point2D MyPoint;
MyPoint.color = 345;
Point2D AnotherPoint = Point2D( MyPoint ); // now AnotherPoint has color = 345
}
}``````

Question 4 :

What is Boyce Codd Normal form?